I'm working on 2D and I have a Quad as background.
And some wall sprites over this quad :
I'm instantiating wall prefab sprites over quad when user click to somewhere. But I don't want to instantiate a wall over another wall, so I'm sending a ray from camera to click point and if hit object is a wall object I won't instantiate.
Here my code :
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
Physics.Raycast(ray, out hit,Mathf.Infinity);
// If it hits ground, not another objects (like walls)
if(hit.transform.name == "GroundQuad")
Instantiate (wall, Input.mousePosition, Quaternion.identity)
But it's still creating wall objects. Tried Debug.Log()
to print hitted object's name to console and moved pointer all over game screen, it's always GroundQuad. So ray not hitting to wall objects.
Can you tell me what is I'm missing? Is it a problem with Layer Collision Matrix ?
Answer
Just figured out the problem. I was using Physics.Raycast
instead of Physics2D.Raycast
. Changed my code like this:
RaycastHit2D hit;
hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition),Vector3.back);
// If it hits ground, not another objects (like walls)
if(hit.transform.name != "Wall")
Instantiate (wall, Input.mousePosition, Quaternion.identity)
Now it's detecting all collisions with objects but not detecting collision with Quad . You can send a comment if you know why it's not detecting quad.
No comments:
Post a Comment