- Home /
Can't Figure out how to make my player jump (2D)
using UnityEngine; using System.Collections;
public class PlayerController : MonoBehaviour {
// Movement Variables
public float moveSpeed = 5F;
public float jumpHeight = 5F;
// Input Variables
public KeyCode moveRight = KeyCode.D;
public KeyCode moveLeft = KeyCode.A;
public KeyCode jumpKey = KeyCode.W;
// Component Variables
private Rigidbody2D rigid;
// Update on Scene Start
void Start()
{
rigid = GetComponent<Rigidbody2D>();
}
// Update Per Frame
void Update ()
{
// Move Right
if (Input.GetKey(moveRight))
{
transform.position += Vector3.right * moveSpeed * Time.deltaTime;
}
// Move Left
if (Input.GetKey(moveLeft))
{
transform.position += Vector3.left * moveSpeed * Time.deltaTime;
}
// Jump (Not Working)
if (Input.GetKeyDown(jumpKey))
{
rigid.AddForce(Vector3.up * jumpHeight);
}
}
}
Answer by Adarn · Sep 18, 2016 at 10:27 PM
Try adding your jump force as an impulse instead of a force. The difference is that an impulse is applied as an instant change to velocity where as the way you are currently applying it (as a force) is more like a push where the force needs to be applied constantly over time to achieve movement, but as you are only doing it on KeyDown the push will only happen for a frame.
To do this pass the ForceMode2D.Impulse to your add force call like this
rigid.AddForce(Vector3.up * jumpHeight, ForceMode2D.Impulse);
Also you should try to do any physics changes in the FixedUpdate instead of the Update. This is the way it is intended as there is only one fixed update call per physics step.