- Home /
How to make a 2D jumping script using Linecast?
I'm starting out with Unity and I'm stuck with making a jumping script. The problem is that the ground check fails and by pressing the jump button, my character just continues to go up.
using UnityEngine;
using System.Collections;
public class Jump : MonoBehaviour {
Vector2 myPos;
Vector2 groundCheckPos;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
myPos = new Vector2 (transform.position.x, transform.position.y);
groundCheckPos = new Vector2 (transform.position.x, transform.position.y);
if (Input.GetKey ("w") && !isGrounded()) {
transform.position += Vector3.up * 20 * Time.deltaTime;
}
}
public bool isGrounded(){
return Physics2D.Linecast(myPos , groundCheckPos , 1 << LayerMask.NameToLayer("Ground"));
}
}
I have added both a layer and a tag called "Ground" to the objects Linecast should work on. What is wrong with the code?
Answer by KellyThomas · Jan 23, 2014 at 02:16 PM
public bool isGrounded(){
bool result = Physics2D.Linecast(myPos , groundCheckPos , 1 << LayerMask.NameToLayer("Ground"));
if (result) {
Debug.DrawLine(myPos , groundCheckPos , Color.green, 0.5f, false);
}
else {
Debug.DrawLine(myPos , groundCheckPos , Color.red, 0.5f, false);
}
return result;
}
Try using this code for your isGrounded()
method. It will draw a debug line that will let you confirm whether groundCheckPos
is in the right spot.
UPDATE:
myPos
, andgroundCheckPos
are currently both being assigned the same values, this means your linecast is of zero length.Input.GetKey()
will return true on each frame the key is held, you may preferInput.GetKeyDown()
.No gravity is applied in this code, are you using a rigidbody for gravity?
groundCheckPos is supposed to refer to an empty game object attached to the player. How do I get its position in the script?
I'm using a rigidbody2D