< Back to Game Dev, Unity

Gravity and Hit Detection in Unity

To add gravity to your main hero (for example) so he falls to physics:

  1. Place the image of the character into the scene and in the inspector click ‘add component’ and select ‘box collider 2d’ or circle collider 2d’ depending on the shape you want to have.
  2. Add the component ‘Rigidbody 2D’, so the object can be affected by gravity and be able to use hit detection with other objects.
  3. Tick ‘Fixed Angle’ if you don’t want the object to turn as it’s falling.
  4. You can change the gravity by going to ‘Edit/Project Settings/Physics 2D’

If you hit the play button the character will fall.

Now to add a floor for hit detection. This can be similar object to the character or an empty object with no sprite. Adding a collider to this object will make the guy stop when he touches the floor object. If you want the to run some code on hit detection then tick ‘Is Trigger’ in the box collider component. The code is added to the guy as a component and goes something like this:

    void OnTriggerEnter2D(Collider2D other)
    {
        if (other.gameObject.CompareTag ("island")) {
            print ("island");
        } else if (other.gameObject.CompareTag ("lava")) {
            print ("gameover");
        }
    }
}

Tags are added to other items so you can tell which object collided with the guy. You add/edit tags in the Inspector.

One thing to note is the gravity/force is relative to the scale of the object being affected. If something is scaled bigger, it will fall slower. For mobile games where you scale to the size of the screen, you’ll have to adjust the forces by something something like:

guyRigidBody.gravityScale = mainStage.transform.localScale.x;

and

jumpForce = 430*mainStage.transform.localScale.x;
guyRigidBody.AddForce(new Vector2(0, jumpForce));

The first line makes it so the bigger the scaling, the more it’s affected by the gravity (ie falls faster).

The 2nd line makes the upward force applied increase with scaling, simulating a jump.

Be Sociable, Share!

Leave a Reply

Your email address will not be published. Required fields are marked *