I’m sure this is very simple, but I have an object (just a cube at the moment) and I want it to jump when I press space.
I have found the code in the help and I can do it fine but only if it has a Character Controller. I don’t want this as I want to use the physics that when this object is hit by a spinning pole on the level it falls over and falls off a platform (a character controller does just pushed off the platform but stays upright).
So I have given it a rigidbody and tried this code:
public class jump : MonoBehaviour {
public float JumpHeight = 2f;
void Update()
{
if (Input.GetButtonDown(“Jump”))
{
GetComponent().AddForce(Vector2.up*JumpHeight);
}
}
}
But nothing happens! Any ideas?
I personally haven’t used the Character Controller, but I do know that it’s good practice to execute code involving physics in the function FixedUpdate. Another thing you could do is increase the value of JumpHeight, 2 just seems a little low to me.
This is what I would try if I were you:
public class jump : MonoBehaviour {
public float JumpHeight = 2f;
private bool isJumping;
// Check for input here:
void Update () {
if (Input.GetButtonDown(“Jump”)) {
isJumping = true;
}
}
// Act on it here:
void FixedUpdate () {
if (isJumping) {
GetComponent().AddForce(Vector2.up*JumpHeight);
isJumping = false;
}
}
}
Hope this helps.
Hello,
Thanks for your code. I have it working now. It was partly that the jump force was far too low, it actually needed to be on 200.
I think setting it higher and your code has fixed it.
Thanks
James