In my 2d game the world is laid out in blocks (Like 2d minecraft) and I am trying to make the player break the block below him when he hits the mine button. Here is my code:
if(Input.GetButtonDown("MineDown"))
{
Transform other = Physics2D.Raycast(new Vector2(gameObject.transform.position.x, gameObject.transform.position.y), new Vector2(Vector3.down.x, Vector3.down.y), Mathf.Infinity).transform;
Destroy(other.gameObject);
}
The only problem is when I press the mine button, the player gets destroyed and not the block below it. This is not the behavior I expected, but I don't know how to fix it.
It's important to understand the physics engine you're using. Some raycast systems ignore a collider if the raycast starts within the collider, and some do not.
Quoting from the manual entry for Physics2D.Raycast
:
this will also detect Collider(s) at the start of the ray.
Your raycast starts inside of the player's collider, so it will always hit it.
Possible workarounds, in roughly the order I'd recommend trying them:
collider.bounds
)Physics2D.RaycastAll
to find all matching colliders, then check what they areA layer mask is pretty easy to set up. You'll need to register a new layer with the tags & layers panel, then use the inspector window to apply that layer to object(s) in your scene. When you have objects on different layers, you can use those to control rendering, collision, raycasting, and so on.
I often have layers for the player, enemies, terrain, and so on.