- Home /
How to check for the ground in Unity 2D for Jumping
So I have this script where I use a timer to prevent jumping, but this is sort of overrided if you jump at a high block and have enough fall time to get the timer to zero, also it is weird for me if I have to wait a second or two even if I'm on the ground and needing to jump. What I want to do is have something check for the ground, and then set a variable to true if im on the ground. If that variable is true, then I can jump. Also I have heard of linecasting, but I don't understand how it works, so if that is your solution can you tell me what the code does along with how linecasting works, because I don't get the Unity description of it.
Here is the script I have right now called "Movement Test":
#pragma strict
var movementSpeed : float = 5.0f;
var jump : float = 0;
var jumpSpeed : float = 5;
var jumpTimer : float = 0;
function Start () {
}
function Update () {
if (jump == 1){
jumpTimer = jumpTimer + 1;
if (jumpTimer >= 85) {
jumpTimer = 0;
jump = 0;
}
}
// This is how the keys work
if(Input.GetKey("a") || Input.GetKey("left")){
transform.position -= Vector3.right * movementSpeed * Time.deltaTime;
} else if(Input.GetKey("d") || Input.GetKey("right")){
transform.position += Vector3.right * movementSpeed * Time.deltaTime;
}
if(Input.GetButtonDown("Jump") || Input.GetKey("w")){
if (jump==0) {
rigidbody2D.velocity.y = jumpSpeed;
jump = 1;
}
}
}
Here is an article I found which explains how to use Physics.OverlapCircle to check if object is grounded. $$anonymous$$aybe it might help someone who is struggling to get this
Answer by Vandarthul · Apr 28, 2014 at 03:56 AM
You can use Physics.Linecast or Raycast to control if you are touching the ground or not. You can check the unity's 2D tutorial and get the idea of using Linecast. There is a script written in that tutorial exactly what you want.
http://pastebin.com/JS3Ktbgp Here is a script that I wrote long time ago that suits your needs + it has double jump too, but be aware of that this is for 3D, you might need to convert it for 2D(Rigidbody2D instead of Rigidbody for example). Also, that this script is old and I wasn't aware of many things back then. But still, you can comb out the areas that you need and/or you can get the idea behind it.