- Home /
Raycasting not behaving as expected?
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.
Thanks, worked!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!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!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
No problem, glad it helped. I converted the comment to an answer, would it be a bother if I ask you to mark it as the accepted answer?
Answer by virgiliu · May 27, 2015 at 12:17 PM
Add a layer mask to your Raycast() so that it hits only the blocks layer and ignores the player. It most likely hits the player first. http://docs.unity3d.com/ScriptReference/Physics2D.Raycast.html
Answer by virgiliu · May 28, 2015 at 11:07 AM
The ray is hitting your player most likely. Add a LayerMask for the blocks and Raycast() only on that layer.
http://docs.unity3d.com/ScriptReference/Physics2D.Raycast.html
Your answer
Follow this Question
Related Questions
2D Raycast Layer Mask not working 1 Answer
Cast multiple rays from an object between two angles? 0 Answers
How can I get the rotation of Handles.DrawLine to match up with an Objects forward? 0 Answers
Maintain equal physics over different UI sizes? 2 Answers
Need help to convert this raycasting 3d Script into a 2D x&y version 0 Answers