Hello, I have a sprite gameobject which is a ball, I want to detect when the player clicks on the ball.
I have tried
RaycastHit hitInfo = new RaycastHit();
if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hitInfo))
{
Debug.Log( hitInfo.transform.gameObject.name );
}
but the ball does not get detected at all… I have added 3D objects to my scene to test it and it works for 3D objects fine…
Does anyone have any idea on what’s wrong?
Thanks.
i changed “Physics.Raycast” to “Physics2D.Raycast” and “RaycastHit” to “RaycastHit2D”
Like that:
RaycastHit2D hitInfo = new RaycastHit2D();
if (Physics2D.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hitInfo)){
Debug.Log( hitInfo.transform.gameObject.name );
}
but i get these errors:
“error CS1502: The best overloaded method match for `UnityEngine.Physics2D.Raycast(UnityEngine.Vector2, UnityEngine.Vector2)’ has some invalid arguments”
and
"
error CS1503: Argument `#1' cannot convert `UnityEngine.Ray' expression to type `UnityEngine.Vector2'"
Where do i make mistake?
You need to pass a Vector2 as the first argument, not a Ray, the second argument should be a Vector2, and the RayCastHit2D is returned by the function. Looks like you’ve just got a bit confused between the Physics.Raycast and Physics2D.Raycast syntax. Try this:
Oups working! I made a mistake in the last post. Here is the working script, hopefully it will help someone!
(not forget to drag and drop the active camera in the camera public slot of the script.)
#pragma strict
public var cam:Camera;
function Start () {
}
function Update () {
if (Input.GetMouseButtonDown(1))
{
var hit : RaycastHit2D = Physics2D.Raycast(cam.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);
if(hit != null)
{
Debug.Log("object clicked: "+hit.collider.tag);
}
}
}
RaycastHit2D is a struct therefore you won’t get a NULL returned but as mentioned the collider will be valid or NULL. However, to save you from having to perform the ugly explicit check whether the collider is null or not, RaycastHit2D has an implicit conversion operator to bool so you can do: