Sunday, 16 August 2015

Unity 5 - Jump and collision problem

I've been having a problem with a small 2D game I'm making in Unity. When the player jumped and collided with a wall, the character would jump higher.

I thought this was a problem with Unity physics as I saw in some other unity answers. But, the solutions they proposed didn't work for me. So, I went back and rechecked my code and saw that I had made my "grounded" variable change to true when the player collided with an object. I think we can all see that's wrong!

Basically, when the player jumped and hit the wall, the "grounded" variable turned back to true. Coupled with the fact that I was using Input.GetAxis, which basically returns a continuous > 0 value while the button is pressed, enabled the player to "double-jump".

So, after thinking for a solution, I searched the net once again and came upon a unity answers post where a user suggested the method used in a unity tutorial to check the grounded state.

(The tutorial is this one, the one with the potato-thing:https://www.assetstore.unity3d.com/en/#!/content/11228 )

The solution to my problem was this:

- Add an empty object under your player object named GroundCheck. Place it just under your player.

- Create a "Ground" layer and set all floors and walking surfaces to that layer.

- Go to your character controller script (whatever it may be called) and declare:
 private Transform groundCheck;
(Make sure you also have a boolean variable called grounded declared.)

- In your Start() function add this line to get a reference to your GroundCheck object:
groundCheck = transform.Find("GroundCheck");

- In your Update() function add this (this checks to see if there is anything from the "Ground" layer between the player and the GroundCheck.):
grounded = Physics2D.Linecast(transform.position, groundCheck.position, 1 << LayerMask.NameToLayer("Ground")); 

If you are like me and used Input.GetAxis to get your jumping, use this instead for your input check: if (Input.GetButtonDown("Jump") && grounded)
{
   //(...other stuff you want to do go here)
   grounded = false;  
}

Hope this helps anyone stuck with the same problem as me. :)