- Home /
I can only jump once on my jump code C#
In my jump script there is a statement that says, if not grounded and moving along the y axis, grounded = true however, this statement doesn't seem to be active.
using UnityEngine;
using System.Collections;
public class Jump : MonoBehaviour {
public bool grounded = true;
public float jumpPower = 50000;
// Use this for initialization
void Start () {
grounded = true;
}
void Update () {
if(!grounded && GetComponent<Rigidbody2D>().velocity.y == 0) {
grounded = true;
}
if (Input.GetButtonDown("Jump") && grounded == true) {
GetComponent<Rigidbody2D>().AddForce(transform.up*jumpPower);
grounded = false;
}
}
}
Is there something wrong within my script? The problem is that I can only jump once.
Answer by Oribow · Apr 05, 2015 at 11:06 PM
Better use raycast instead of checking the velocity. Its more accurate.
If(Physics.Raycast(transform.position-transform.localscale/2, Vectore3.Down, 0.1f)
//IsGrounded = true;
Answer by Keearix · Apr 06, 2015 at 02:16 PM
You can use the method called OnCollisionEnter2D.
As long as your ground has a tag set to Ground, which can be done at the top of the inspector, this script works.
Here is an example jump script that works perfectly :
using UnityEngine; using System.Collections;
public class playerMovement : MonoBehaviour {
public float jumpSpeed = 50f;
public bool grounded = false;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (grounded) {
if (Input.GetKey (KeyCode.Space)) {
GetComponent<Rigidbody2D> ().AddForce (Vector2.up * jumpSpeed);
grounded = false;
}
}
}
void OnCollisionEnter2D (Collision2D other){
if (other.transform.tag == "Ground") {
grounded = true;
}
}
}
This code assumes that whenever you press the jump key, you exit the collision with the ground, which isn't always true in all games. For example, if you jump but are blocked by a low ceiling, you might not exit the collision with the ground, which means that OnCollisionEnter() method would never trigger. You won't be able to jump until you triggered OnCollisionEnter() some other way.
For some games, this can be a problem, and raycasting would solve that.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Jumping through the roof! 1 Answer
Preventing Rotated Jumping (C#) 1 Answer