1
\$\begingroup\$

I'm working on 2D and I have a Quad as background.

enter image description here

And some wall sprites over this quad :

enter image description here

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 ?

\$\endgroup\$
0
\$\begingroup\$

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.

\$\endgroup\$
  • 2
    \$\begingroup\$ Because Quad and its Mesh Collider belong to 3D physics. \$\endgroup\$ – Maxim Kamalov Sep 15 '15 at 18:05
  • \$\begingroup\$ So what you suggesting? Using Quad is bad idea for background? \$\endgroup\$ – Eray Sep 15 '15 at 18:06
  • \$\begingroup\$ Isn't it easier to just use sprites for everything? \$\endgroup\$ – Maxim Kamalov Sep 15 '15 at 18:17
  • \$\begingroup\$ I'm tiling all quad surface with a little (32x32) grass image. \$\endgroup\$ – Eray Sep 15 '15 at 18:19
  • \$\begingroup\$ Then why not just think this way: unsuccessful ray-cast = no walls were hit = background was hit. \$\endgroup\$ – Maxim Kamalov Sep 15 '15 at 18:22
0
\$\begingroup\$

Try to attach the normal Box Collider with your sprite ray cast will detect that. I have also faced the same issue with this 2D Box Collider so i just used the normal box collider.

Performance wise its 2d collider only best but you dont get that much performance lag.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.