- Home /
How do I make the player jump at a fixed height?
I've been tinkering with the code, but I can't find anything that works. I'm making a 3D game, and writing in C#. Here's the code that I have now.
public class PlayerController : MonoBehaviour {
public float speed;
public float jumpHeight;
private Rigidbody rb;
void Start ()
{
//Got too lazy, so added this in.
rb = GetComponent<Rigidbody>();
}
void FixedUpdate ()
{
//Movement on the X and Z axes
float moveHorizontal = Input.GetAxis ("Horizontal");
float moveVertical = Input.GetAxis ("Vertical");
Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);
rb.AddForce (movement * speed);
// The Jump Code
if (Input.GetKeyDown (KeyCode.Space))
{
Vector3 jump =new Vector3 (moveHorizontal, jumpHeight, moveVertical);
rb.AddForce (jump);
}
}
}
Now what? I want to do this in the shortest and the most efficient way possible, without using too many variables.
Answer by RobAnthem · Apr 02, 2017 at 11:02 AM
First suggestion, don't use AddForce for movement, it's basically the worst thing you can do to move a player. Use Velocity. After that, you can literally just AddForce to jump like this.
rb.AddForce(transform.up * jumpHeight);
Or you can incorporate it into your velocity mechanism and scale or lerp the height over time to smooth it out. Also you need to smooth your movement out a bit. I wrote a tutorial on this, you can find it here. Proper Velocity-Based Movement 101
Answer by toddisarockstar · Apr 02, 2017 at 06:15 PM
if your game is 3d and Y is up, this should get you moving:
public class PlayerController : MonoBehaviour {
public float speed;
public float jumpHeight;
private Rigidbody rb;
void Start ()
{
//Got too lazy, so added this in.
rb = GetComponent<Rigidbody>();
}
void FixedUpdate ()
{
//Movement on the X and Z axes
float moveHorizontal = Input.GetAxis ("Horizontal");
float moveVertical = Input.GetAxis ("Vertical");
Vector3 movement = new Vector3 (moveHorizontal, rb.velocity.y, moveVertical);
rb.velocity=movement*speed;
// The Jump Code
if (Input.GetKeyDown (KeyCode.Space))
{
rb.AddForce (Vector3.up*jumpHeight);
}
}
}
The movement is good, but when I jump, it seems to teleport to a higher location and descend slowly, as if there was no gravity at all.
Your answer
Follow this Question
Related Questions
First person skydiver help 1 Answer
How to jump always with the same height 1 Answer
How to make a physics based jump with button hold effect 0 Answers
Jump with physics 1 Answer
why does my train jump off the tracks? 0 Answers