Unity Physics2D.Raycast hits itself

前端 未结 2 1466
傲寒
傲寒 2020-12-06 23:21

I\'m trying to use Physics2D.Raycast in order to check if the player is on the ground (I know that there are other approaches to check if the player is on the g

相关标签:
2条回答
  • 2020-12-06 23:47

    Vector2.down vector does not present the object space's down vector all the time. You can use -transform.up.

    Also, if it is acceptable you can add some padding to start point of the ray, like rayOrigin.y += 0.0001f;.

    0 讨论(0)
  • 2020-12-07 00:10

    The problem is occurring because your Player is overlapping at the start of the raycast. There are few ways to fix this:

    1.Disable Queries Start In Colliders.

    Go to Edit->Project Settings->Physics 2D then make sure that Queries Start In Colliders is NOT checked. Your code ran fine after changing that. Here is a screenshot:

    2.Another solution is to use layers.Raycasting but ignoring the Player layer.Before you do that, make sure to create a layer called Ground and put your ground GameObject to the Ground layer then create another layer called Player and put your player in the Player layer. We can now use bitwise operator to exclude Player layer from the raycast.

    Now, lets assume that Player layer number is 9. The code below should fix your problem.

    public int playerLayer = 9;
    int layerMask = ~(1 << playerLayer); //Exclude layer 9
    RaycastHit2D hit = Physics2D.Raycast(rayOrigin, Vector2.down, 0.1f, layerMask);
    

    That's it. Both of these were able to solve your problem.

    For other people reading, below are other ways to easily detect when Player is touching the floor without using Physics2D.Raycast or doing all those things above.

    Simply attach to the Player.

    public class Player : MonoBehaviour
    {
        public LayerMask groundLayer;
        Collider2D playerCollider;
        bool grounded;
    
        void Start()
        {
            playerCollider = gameObject.GetComponent<Collider2D>();
        }
    
        public bool IsGrounded()
        {
            grounded = Physics2D.OverlapCircle(playerCollider.transform.position, 1, groundLayer);
            return grounded;
        }
    }
    

    Or you can use IsTouchingLayers.

    public bool IsGrounded()
    {
        grounded = grounded = playerCollider.IsTouchingLayers(groundLayer.value);
        return grounded;
    }
    
    0 讨论(0)
提交回复
热议问题