Search code examples
c#collision-detectioninterpolationunity-game-engine

Interpolate object collision stuck


I am working on a very basic test in Unity 2D. The problem I am having is when my sprite collides with the ground it is constantly checking the event, almost too frequently, so the sprite stays in limbo. It doesn't have a chance to leave the ground as by the time it does the check tells it to turn around resulting it quickly going up and down. As shown in the below clip:

https://m.youtube.com/watch?v=gPmmLjGe9iQ

What I want is when contact is made the sprite needs to change it's Y axis direction. Please see my code below.

void Update () {
    hitWall = Physics2D.OverlapCircle(wallCheckUp.position, wallCheckRadius, whatIsWall);
    if (hitWall)
    {
        moveUp = !moveUp;
    }

    if (moveUp)
    {
        transform.localScale = new Vector3(-1f, 1f, 1f);
        GetComponent<Rigidbody2D>().velocity = new Vector2(speed, GetComponent<Rigidbody2D>().velocity.x);
    }
    else
    {
        transform.localScale = new Vector3(1f, 1f, 1f);
        GetComponent<Rigidbody2D>().velocity = new Vector2(-speed, GetComponent<Rigidbody2D>().velocity.x);
    }
}

If more information is needed please let me know.

EDIT

To make what I have clearer please see my sprites settings.

enter image description here


Solution

  • OverlapCircle checks for any overlap, so if as long as there is overlap between it and an object, it will be true, thus running your if statement for every frame that it's true. Try using the method OnCollisonEnter2D or OnTriggerEnter2D (just replace the name of the method):

    void OnCollisionEnter2D(Collision2D coll)
    {
        moveUp = !moveUp;
        if (moveUp)
        {
            transform.localScale = new Vector3(-1f, 1f, 1f);
            GetComponent<Rigidbody2D>().velocity = new Vector2(speed,  GetComponent<Rigidbody2D>().velocity.y);
        }
        else
        {
            transform.localScale = new Vector3(1f, 1f, 1f);
            GetComponent<Rigidbody2D>().velocity = new Vector2(-speed, GetComponent<Rigidbody2D>().velocity.y);
        }
    }
    

    Also make sure your objects each have a Collider2D in the inspector.

    One more thing. When initializing a Vector2 the order of the arguments is x,y. I noticed that in your code you were using GetComponent().velocity.x (horizontal) in the argument for the y (vertical) component. If your sprite is moving up and down, then that might be the cause of your error, as its y component isn't changing (unless you have some other code that alters the x component).

    So you want to change

    new vector2(speed[-speed], GetComponent<Rigidbody2d>().velocity.x)
    

    to

    new vector2(GetComponent<Rigidbody2d>().velocity.x, speed[-speed])
    

    Hope this helped.