- Home /
How can I make my jumping only work when I'm touching the ground?
Here is my script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Sprites;
public class PlayerController : MonoBehaviour
{
public float speed;
public float jumpSpeed;
public Rigidbody2D rb;
private Vector3 movement;
void Start ()
{
rb = GetComponent<Rigidbody2D>();
}
void Update ()
{
transform.rotation = new Quaternion (0.0f, 0.0f, 0.0f, 0.0f);
if (Input.GetKey (KeyCode.A))
{
transform.Translate (-Vector3.right * Time.deltaTime * speed);
}
if (Input.GetKey (KeyCode.D))
{
transform.Translate (Vector3.right * Time.deltaTime * speed);
}
if (Input.GetKeyDown (KeyCode.Space))
{
rb.AddForce (transform.up * jumpSpeed);
}
}
}
I need help editing this script so that I can only jump when I am touching the ground. Can someone please help me? This is my Player Controller script.
Answer by BattiestMist · Jun 23, 2017 at 12:52 AM
I would use a short-ranged raycast to check if the player is touching the ground. The range of the raycast should be just long enough to hit the ground when the player is touching it. If you need an example to view, add the Unity Default Assets to your project and view the "FirstPersonController" script. It has a section which only allows jumping when the player is touching the ground.
If the ray cast goes down from the center of the gameObject and the gameObject is at a ledge it is possible for the raycast to miss. This would make it impossible for the player to jump at a ledge, presumably the place most people will try to jump from.
Answer by Manpreet_96 · Jun 23, 2017 at 02:24 AM
@Linkthehylian04 Another approach to this could be, an older method but easier to understand, setup a bool flag on jump and activate it only if you are colliding the ground....like your could be like this...
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Sprites;
public class PlayerController : MonoBehaviour
{
public float speed;
public float jumpSpeed;
public Rigidbody2D rb;
private Vector3 movement;
private bool canJump=true;
void Start ()
{
rb = GetComponent<Rigidbody2D>();
}
void Update ()
{
transform.rotation = new Quaternion (0.0f, 0.0f, 0.0f, 0.0f);
if (Input.GetKey (KeyCode.A))
{
transform.Translate (-Vector3.right * Time.deltaTime * speed);
}
if (Input.GetKey (KeyCode.D))
{
transform.Translate (Vector3.right * Time.deltaTime * speed);
}
if (Input.GetKeyDown (KeyCode.Space)&&canJump)
{
rb.AddForce (transform.up * jumpSpeed);
canJump=false;
}
}
//Here check for collision with ground and reset the cool flag
void OnCollisionEnter(Collision col) {
if (col.gameObject.tag == "ground") {
canJump=true;
}
}
}