- Home /
My jump script doesn't work every time
Hey I am trying to write a jump script, the problem is that when I press the P key sometimes the character jumps and sometimes it doesn't. I would appreciate any help I can get.
Here is the code:
public void Update()
{
if (Controller.isGrounded) {
if (Input.GetKeyDown (KeyCode.P)) {
vSpeed = JumpSpeed;
}
}
vSpeed -= Gravity * Time.deltaTime;
MoveDirection.y = vSpeed;
}
$$anonymous$$aybe Controller.isGrounded is not always true.
Answer by StevenUnu · Sep 12, 2017 at 06:54 AM
Try using a rigidbody and AddForce:
public void Update() {
if(Controller.grounded) {
if(Input.GetKeyDown(KeyCode.P))
rb.AddForce(Vector3.up * jumpSpeed * Time.deltaTime) ;
}
}
Hi, thanks for your answer! I tried it but it doesn't do anything. Am I missing something?
@ogotera did it give you an error if so please tell me.
Answer by Litleck · Sep 12, 2017 at 10:18 PM
Make sure you have a rigid body on your character and it has a mass of 1 then make a script and name it Controller with this script.
using UnityEngine;
public class Controller : MonoBehaviour
{
public float jumpPower = 5;
private bool grounded;
Rigidbody rbody;
private void Start()
{
rbody = this.GetComponent<Rigidbody>();
}
void Update()
{
if (!grounded && rbody.velocity.y == 0)
{
grounded = true;
}
if (Input.GetKeyDown(KeyCode.P) && grounded == true)
{
rbody.AddForce(transform.up * (jumpPower*100));
grounded = false;
}
}
}
It isn't perfect because if spammed you can double jump but it works and hopefully it can help you and it'll be further improved.
Hope this helps!
The script works but I would like to use it with a movement script using a Character Controller. If I use both then the jump script doesn't work anymore. Any ideas?
Your answer
Follow this Question
Related Questions
gravity doesnt seem to effect my first person controller....help! 1 Answer
The faster it goes, the longer it jumps 1 Answer
Edit this script so that on the second jump change the gravity to 5 2 Answers
The faster my character goes the longer he jumps. 1 Answer
How to make a object jump constantly at y and move to the next position to z (perfectly) 0 Answers