- Home /
Fixed jump height
Hello there.
I followed some tutorial on youtube and I have done the same thing for my endless runner game. The problem is sometimes jump height is random, but I want it to be always the same. Any solution ?
Here is my script
[code] using UnityEngine; using System.Collections;
public class JumpScript : MonoBehaviour {
public float jumpHeight;
public Transform groundCheck;
public float groundCheckRadius;
public LayerMask whatIsGround;
private bool grounded;
float jumpTime, jumpDelay = 0.0f;
bool jumped;
private bool doubleJumped;
Animator anim;
// Use this for initialization
void Start () {
anim = GetComponent<Animator>();
}
void FixedUpdate(){
grounded = Physics2D.OverlapCircle (groundCheck.position, groundCheckRadius, whatIsGround);
}
// Update is called once per frame
void Update () {
if (grounded)
doubleJumped = false;
if (Input.GetKeyDown (KeyCode.Space) && grounded) {
GetComponent<Rigidbody2D> ().velocity = new Vector2 (0, jumpHeight);
anim.SetTrigger("Jump");
jumped = true;
}
if (Input.GetKeyDown (KeyCode.Space) && !doubleJumped && !grounded) {
GetComponent<Rigidbody2D> ().velocity = new Vector2 (0, jumpHeight);
doubleJumped = true;
}
jumpTime -= Time.deltaTime;
if (jumpTime <= 0 && grounded && jumped)
{
anim.SetTrigger ("Land");
jumped = false;
}
}
}
[/code]
Comment
GetComponent ().velocity = new Vector2 (0, jumpHeight);
Here you are setting the velocity of object, not the jumpHeight. But if you don't modify it's velocity anywhere else, the jumpHeight should be the same all the time as long as the jumpHeight value is the same.
Btw, it is better to do physics in FixedUpdate, not in Update.