Raycast not hitting objects

Viewed 89

It's like a mario game. The player is jumping around and has to collect some items.

The problem is that my ray isn't colliding with the item box colliders.

I need the ray to know, so i can destroy the right item that the player has collided.

void OnCollisionEnter2D(Collision2D colisor)
{
    if((colisor.gameObject.name == "floor" || colisor.gameObject.name == "floor2" || colisor.gameObject.name == "floor3"))
    {
        anim.SetBool("jump", false);
        anim.SetFloat("speed", 0);
    }

    if (colisor.gameObject.name == "space(Clone)")
    {
        RaycastHit hit;
        Ray ray = new Ray(player.position, transform.right);
        Debug.Log("hit1");

        if (Physics.Raycast(ray, out hit))
        {
            BoxCollider bc2d = hit.collider as BoxCollider;
            Debug.Log("hit2");

            if (bc2d != null)
            {
                Destroy(bc2d.gameObject);
            }
        }
    }
}
2 Answers

You're mixing 3d and 2d physics; Physics will only look for 3d objects, so you should be using Physics2D instead. This raycast may still fail if the cast starts inside the target, because the surface normals point in the wrong direction.

Also note that since you already have the Collision2D, you can just grab the otherCollider and shouldn't need to raycast in the first place.

Related