I have an empty 3D GameObject that is serving as the player in a game that I am building. I am trying to write a script that enables the player to “jump” when SPACE
is pressed. I want to do this using kinematic equations, and with only transform.Translate
. Here is the code I have so far:
public float fallingSpeed;
void Update () {
if (Input.GetKey (KeyCode.Space)) {
Jump ();
}
}
public void Jump () {
float yPosition = 0.5f;
// Don't let player fall through floor
if (transform.position.y <= 0.5f) {
fallingSpeed = 0.0f;
} else {
fallingSpeed -= 9.8f * Time.deltaTime;
yPosition += fallingSpeed * Time.deltaTime;
}
// Translate y-position
transform.Translate (new Vector3 (0.0f, yPosition, 0.0f));
}
Currently, when SPACE
is pressed, the player launches into the air and doesn’t come back down. I have tried tinkering with the logic for some time, but can’t seem to wrap my head around why it’s not working.
Any help is appreciated!
EDIT: it seems as though my player reacts well to the mechanics I have set up… when SPACE
is held down. As soon as you let go, the player hangs at whatever y-position he is currently situated, and doesn’t move until you press SPACE
again. How do I get him to keep falling even when I let go of SPACE
? Will that have to be in the Update()
method? Thanks!