Home Ask Login Register

Developers Planet

Your answer is one click away!

Craig Watson February 2016

Raycast in Unity2D can't seem to find the floor

I'm currently trying to use raycast to let my game know when my character is in the air, or more importantly when he is on the ground. A simple raycast should do the trick but no matter what I try it keeps returning false. Both my player and floor have colliders attached, here is the relevant code.

pragma strict

    var leftKey: KeyCode;
    var rightKey: KeyCode;
    var jumpKey: KeyCode;
    var playerSpeed = 7;
    var onFloor = false;
    var distToGround: float;

    function Start () {
        // get the distance to ground
       distToGround = GetComponent.<Collider2D>().bounds.extents.y + 0.1f;

     function IsGrounded(): boolean {
       return Physics.Raycast(GetComponent.<Collider2D>().bounds.center, Vector3.down, distToGround, 1 << 8);

    function Update () {
        Debug.Log("" + IsGrounded());
        if (IsGrounded()){
                GetComponent.<Rigidbody2D>().velocity.x = playerSpeed * -1;
            } else if(Input.GetKey(rightKey)){
                GetComponent.<Rigidbody2D>().velocity.x = playerSpeed;

                GetComponent.<Rigidbody2D>().AddForce(new Vector2(0,380));
        } else if (!IsGrounded()) {
                GetComponent.<Rigidbody2D>().AddForce(new Vector2(-2,0));
            } else if(Input.GetKey(rightKey)){
                GetComponent.<Rigidbody2D>().AddForce(new Vector2(2,0));

I've been stuck on this for a while now and I'm pretty sure I'm just an idiot who is missing something simple or I've been reading out of date materials.


andeart February 2016

Two things:

  1. Your IsGrounded() function has a typo. It should be GetComponent<Collider2D>(), not GetComponent.<Collider2D>()

  2. Try increasing the value of your distToGround float, just in case the RayCast is going in the right direction, but not far enough.

I hope that helps!

Post Status

Asked in February 2016
Viewed 3,394 times
Voted 10
Answered 1 times


Leave an answer

Quote of the day: live life