2D Weird Jumping

Hello,

I’m making a 2D platformer with Unity 5.3. I’ve created a simple jumping code that supports single jumps but there’s a weird action; when player collide with platform from side player launches itself to space! Before code, here’s my collision boxes:


I think a single box collider mixing up things, so I changed my collision boxes in different GameObjects. But anything doesn’t change.

Here’s the jumping code:

using UnityEngine;
using System.Collections;

public class Player : MonoBehaviour {

	public float speed = 25;
	public float jumpSpeed = 1;

	bool isGrounded = false;
	
	// Update is called once per frame
	void Update () {
	
		if((Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.UpArrow) || Input.GetKey(KeyCode.Space)) && isGrounded)
		{
			rigidBody.AddForce(new Vector2(0, jumpSpeed * 100));
			isGrounded = false;
		}

		if(Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.LeftArrow) || Input.GetKey(KeyCode.RightArrow))
		{
			if(isGrounded)
			{
				//changeState(STATE_WALK);
			}
		} else
		{
			if(isGrounded)
			{
				//changeState(STATE_IDLE);
			}
		}

		Vector3 newPos = new Vector3(Input.GetAxis("Horizontal") * speed * Time.deltaTime, 0, 0);
		transform.position += newPos;

	}

	void OnCollisionEnter2D(Collision2D coll)
	{
		if (coll.collider.tag == "Platform") {
			isGrounded = true;
		}
	}

}

Also a video: - YouTube

I can’t figure out this. Thanks for your help, in advance!

The problem is GetKey, which returns true while you hold the key down. When you are on top of the platform that’s not creating a problem because as soon as you jump isGrounded returns false in the next frame and prevents further force from being applied. Not so lucky when you hit the platform from the side, because now isGrounded returns true multiple frames, applying the jump force multiple times over.

The solution:

  • I’d recommend switching to GetKeyDown which returns true only in the first frame a key is pressed. This is what you want if you want single jumps with fixed height. You’ll have to use a different mechanism for sustained jumps (where height is based on how long you keep the key pressed).
  • Instead of setting isGrounded value with collision events, you’d be better off with a downward raycast. This way you will avoid isGrounded returning true when you hit platforms from the side. I believe Unity platformer tutorial explains how to set this up.