Create jumping motion with only transform.Translate
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!
Answer by david-1495 · May 19, 2018 at 03:09 PM
one word : rigidbody
Each rigidbody takes computation, so less are of course ideal. Rigidbodies also have the ability to sleep when their angular and translational velocity drop below a certain threshold. When this happens, the amount of computation they require drops significantly and remains low until they have a force manually applied to them or a collider touches their collider if it exists. https://wiki.unity3d.com/index.php/General_Performance_Tips
Sometimes is better to avoid rigidbody when possible
The solution is simple. You have:
void Update () {
if (Input.GetKey (KeyCode.Space)) {
Jump ();
}
And in your Jump function is:
} else {
fallingSpeed -= 9.8f * Time.deltaTime;
yPosition += fallingSpeed * Time.deltaTime;
}
Your falling logic is in the bottom half of your jump script but you're only calling it if the SPACE button is being pressed. Try putting your falling logic in a different function entirely and call Fall() if you are above the floor.
public float fallingSpeed;
private void Update () {
if (Input.GetKey(KeyCode.Space)) {
Jump ();
}
Fall();
}
public void Jump () {
float yPosition = 0.5f;
}
void Fall() {
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));
}
I hope this helped :)