简体   繁体   中英

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()){
            if(Input.GetKey(leftKey)){
                GetComponent.<Rigidbody2D>().velocity.x = playerSpeed * -1;
            } else if(Input.GetKey(rightKey)){
                GetComponent.<Rigidbody2D>().velocity.x = playerSpeed;
            } 

            if(Input.GetKeyDown(jumpKey)){
                GetComponent.<Rigidbody2D>().AddForce(new Vector2(0,380));
            } 
        } else if (!IsGrounded()) {
            if(Input.GetKey(leftKey)){
                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.

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM