- Home /
How can I make a good jumping script?
Can someone help me make a jumping script? This is what I have so far:
if (Input.GetKey (KeyCode.space))
{
}
I want the jumping to be fairly smooth, like really jumping. Not like teleporting into the air and falling.
Answer by FlaSh-G · Jun 22, 2017 at 02:44 PM
This depends on how your character is designed. If you are using a CharacterController, the answer will be completely different to when you have a Rigidbody based character. If you have neither, your current movement code is likely to make you very unhappy very soon.
Since you stated that you are using a CharacterController: You must have a script for movement already. Something that throws a vector into CharacterController.Move. Something more or less like this:
private CharacterController controller;
private Vector3 movement;
void Awake
{
controller = GetComponent<CharacterController>();
}
void FixedUpdate()
{
movement = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
movement = Vector3.ClampMagnitude(movement, 1);
controller.Move(movement * Time.deltaTime);
}
The idea now is that you add a gravity variable, and a jump power. You check if the controller is grounded, and if it is, you set movement.y to the jump power value, and if it is not, you subtract gravity times Time.deltaTime from it.
void Update()
{
if(Input.GetButtonDown("Jump"))
{
jump = true;
}
}
void FixedUpdate()
{
if(controller.isGrounded)
{
movement = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
movement = Vector3.ClampMagnitude(movement, 1);
if(jump)
{
movement.y = jumpPower
}
else
{
movement.y = -1; // To stay grounded rather than floating above the ground
}
}
else
{
movement.y -= gravity * Time.deltaTime;
}
jump = false;
controller.Move(movement * Time.deltaTime);
}
This should give you something to work upon.
@FlaSh-G Can you please actually help me? This wasn't a helpful answer
I couldn't give you a useful answer because you didn't provide enough information to do so. With your other anwer, you did.
Answer by Linkthehylian04 · Jun 22, 2017 at 03:15 PM
@FlaSh-G I am using both Rigidbody and a PlayerController script. Can you please tell me how I can add jumping to that script?
Your answer
![](https://koobas.hobune.stream/wayback/20220612124705im_/https://answers.unity.com/themes/thub/images/avi.jpg)