Alina
Alina

Reputation: 444

Rigidbody2D stops when hits collider

I've got a player with Rigidbody2D and circle collider attached to it. The player collects coins which have circle collider. I move the player left and right. When it collects a coin, the coin destroys and player stops, so I have to touch again to continue moving left/right. So, how to collect coins without stopping player? Here is my code that moves rigidbody:

void TouchMove()
{
    if (Input.touchCount > 0)
    {
        Touch touch = Input.GetTouch(0);
        float middle = Screen.width / 2;

        if (touch.position.x < middle && touch.phase == TouchPhase.Began)
        {
            MoveLeft();
        }

        else if (touch.position.x > middle && touch.phase == TouchPhase.Began)
        {
            MoveRight();
        }
    }
    else
    {
        SetVelocityZero();
    }
}

public void MoveLeft()
{
    rb.velocity = new Vector2(-playerSpeed, 0);
}

public void MoveRight()
{
    rb.velocity = new Vector2(playerSpeed, 0);
}

public void SetVelocityZero()
{
    rb.velocity = Vector2.zero;
}

Upvotes: 2

Views: 60

Answers (1)

Programmer
Programmer

Reputation: 125275

Your coins should not be able to collide with any object especially the player.

Make the collider of the coin to be trigger then use OnTriggerEnter2D to detect when it touches the player in order to destroy the coinf instead of OnCollisionEnter2D.

enter image description here

Attach to your coin GameObject:

void OnTriggerEnter2D(Collider2D collision)
{
    if (collision.gameObject.CompareTag("Player"))
    {
        Debug.Log("Player detected. Destroying this coin");
        Destroy(gameObject);
    }
}

Or Attach to your player GameObject:

void OnTriggerEnter2D(Collider2D collision)
{
    if (collision.gameObject.CompareTag("Coin"))
    {
        Debug.Log("Coin detected. Destroying coin");
        Destroy(collision.gameObject);
    }
}

Upvotes: 1

Related Questions