Setup:
I have the project setup in 2D (the camera’s projection is orthographic). The scene contains only 1 camera and a sprite.
The sprite has a Circle Collider 2D component and its bounding circle encompasses the entire sprite.
The camera contains the following script :
void Update()
{
GameObject.Find("MousePositionText").guiText.text =
Input.mousePosition.x.ToString() + ", " + Input.mousePosition.y.ToString();
if( Input.GetMouseButtonDown(0) )
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay( Input.mousePosition );
if( Physics.Raycast(ray, out hit) )
GameObject.Find("TargetHitText").guiText.text = "We clicked on the sprite!";
else
GameObject.Find("TargetHitText").guiText.text = "We missed the sprite!";
}
}
The camera is positioned at (0,0,-10) with its near plane = 0.3 and far = 1000.
The sprite is positioned at (-4,2,0)
I keep on getting “We missed the sprite!” every single time I click on the sprite. Can someone help me out? Thanks!
Try the Physics2D.Raycast.
RaycastHit2D hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if(Physics2D.Raycast(ray, out hit))
I don’t think the Physics2D.Raycast is the correct API I should be using for this purpose. From the documentation (Unity - Scripting API: Physics2D.Raycast) it seems like it’s only for casting a ray along the xy-plane, where as I want to cast a ray from from a point on screen into the 3D world.
Anyway, I changed the camera’s projection to Perspective and it still doesn’t work… so maybe it’s not an issue with whether it’s orthographic or not but something else I’m doing wrong?
There isn’t any support for that yet but Unity has said it will be added. You could use a tiny circle collider trigger instead and just check if it fires a message.
Sooo… I just found out something interesting… if I create a cube in the scene and I click on it, this
if( Physics.Raycast(ray, out hit) )
GameObject.Find("TargetHitText").guiText.text = "We clicked on the sprite!";
is true and the appropriate text appears.
Why does it work with 3D objects but not sprites?
Because it’s part of Physx only, not Box2D.
Do you mean that there isn’t any support for raycast detection against sprites?
[edit]
Oh I see…