Need help with Movement Physics

Heya all,

So Im new to Unity and C#, so please dont bash me in too hard ! :smile:
Im attempting to make a way for a player to “glide” through the air if they were to jump and move forward. THey cannot move while in mid air, but if they already issued a forward as they did the jump command, then they would move forward and jump. However, with the code below, they only jump when the conditions are met?

I’ve tried the following:

if(forward && sprint && jump){
GetComponent<Rigidbody>().AddForce(Vector3.forward * sprintSpeedCalc);
GetComponent<Rigidbody>().AddForce(Vector3.up * jumpPower * Time.deltaTime);
Debug.Log("forward && sprint && jump");
}

and

if(forward && sprint && jump){
GetComponent<Rigidbody>().AddForce((Vector3.forward * sprintSpeedCalc) + (Vector3.up * jumpPower * Time.deltaTime));
Debug.Log("forward && sprint && jump");
}

The whole script: https://pastebin.com/J3tKKLzH

Bump

Can you clarify what you mean by “they only jump when the conditions are met” as being the problem? But my first guess as to the issue is that sprintSpeedCalc is too small of a number for the force you’re looking for. Your jumps are taking a force of jumpPower * deltaTime, where jumpPower is 10,000, but your forward force is 2.5 * 2 * deltaTime. Tiny. Try hardcoding in a large number for the forward force and see it if actually moves. If so you can then work on the variable values you need to get the correct force.

There’s some possibly unrelated issues with your code though I’d like to point out.

*FixedUpdate happens at a set schedule, but you’re multiplying all your forces by deltaTime which will never be different between FixedUpdate calls. That’s unnecessary and not really recommended.

  • You’re getting keyboard input in FixedUpdate. This is a bad idea. GetKey returns true on any frame where they key is down, but FixedUpdate is frame rate independent. There can be 0 or many frames between calls to FixedUpdate. So you can miss key presses or other related issues. It is best to get your input in Update, set your bools there, and act on them for physics movement in FixedUpdate.

  • You’re mixing setting the transform.position directly with physics movement using forces. These usually don’t go together outside of intentionally teleporting a physics object. You’ll have issues where you are getting unexpected physics behavior.

  • You’re doing transform.position movement from FixedUpdate, where it should instead be done in Update. That is because of what I said earlier where there can be multiple frame updates between calls to FixedUpdate, which will produce stuttered movement.