- Home /
Checking if grounded with Linecast not working (2D)
So I am trying to make a dead-simple platformer. Here is the entirety of the script I have right now:
using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour
{
//An empty child of the PlayerController with only a position
private Transform GroundCheck;
//Use this for initialization
void Start()
{
//Find the GroundCheck
GroundCheck = transform.Find("GroundCheck");
}
//Update is called once per frame
void Update()
{
//Check whether or not the player is grounded
bool IsGrounded = Physics2D.Linecast(transform.position,
GroundCheck.position,
0);
//Start by adding jumping!
if (Input.GetButton("Jump") &&
IsGrounded == true)
{
Debug.Log("JUMP");
rigidbody2D.AddForce(new Vector2(0, 1) * 100);
}
}
}
Unfortunately, no dice. The terrain has a CollisionBox and is on layer 0, and the player has a rigidbody2D and is on Layer 1. If I cast without specifying a layer, or specify layer 1, the player jumps infinitely, as Linecast always returns true. If I cast specifying layer 0, which is where I expect the terrain to be, nothing ever happens and the player never jumps.
I made sure that the pivot of the 2D character is at its Bottom and not its center, so presumably the Linecast shouldn't be detecting the character itself, right? And why is it not detecting the terrain at all? I don't understand what's going on.
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 fafase · Jan 16, 2014 at 05:59 AM
It could be a wrong use of linecast. I also get quite confused on what I should get and how to use it.
Here is an example taken from http://unitygems.com/basic-ai-character/#Sight:
Transform GroundCheck;
int layerMask = 1 << 8;
void Start(){
GroundCheck = transform.Find("GroundCheck");
layerMask = ~layerMask;
}
void Update(){
Debug.DrawLine (_transform.position, GroundCheck.position, Color.yellow);
if (Physics.Linecast (_eyes.position, GroundCheck.position, layerMask)) {
// Grounded
}
}
I don't feel I know what's going on with layer masks there. Why use 1 and 8? Where should I look to find what numbers I should use in my game? EDIT: Never$$anonymous$$d, I think I've figured it out. It seems to work now, except that it occasionally registers a double-jump ins$$anonymous$$d of a single-jump, even with the tiniest possible length of Linecast.
This 1<<8 thing is bit manipulation. There are more straight forward to do that but we'll...it just means you set bit number 8 with a 1.
Your answer
![](https://koobas.hobune.stream/wayback/20220613130553im_/https://answers.unity.com/themes/thub/images/avi.jpg)