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

Unity 2D C# - Collider not working


I am working on a 2D TopDown game in Unity 5. The collision is not working at all. The player and the obstacle both have a 2D Collider and they are not Trigger. The player has a 2D Rigidbody with Kinematic set to false, gravity scale is equal to zero. Maybe the movement code has something to do with it. The code is a bit long so I'll just show you the code for moving up:

if (Input.GetAxis ("Up") > 0) {

    if (movingDown == false) {

        posY += speed * Time.deltaTime;
        movingUp = true;
    }
} else {

    movingUp = false;
}

/.../

transform.position = new Vector3 (posX, posY, 0);

It is always setting the value of the position as long as you are pressing the up button. Is there a way to fix this?


Solution

  • I think that the problem is that you are setting the position directly. So at each frame, you are telling unity exactly were the object should be, which overrides the position that would be computed from collision.

    To fix this, you need to modify your movement code to add a force to your rigidbody and leave the position untouched ( see rigidbody doc, and function AddForce (https://docs.unity3d.com/ScriptReference/Rigidbody.html)