Question by
bhavinbhai2707 · Mar 07, 2018 at 07:48 PM ·
scripting problemraycastraycasthit2d
Need help in Raycast2D!!
Hey i want to raycast a ray from my touch position to the sprite(box collider 2d) on which i click.
private GameObject getObject(Vector2 touchPos)
{
RaycastHit2D hitInfo = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(touchPos),Vector2.up);
Debug.DrawLine(Camera.main.ScreenToWorldPoint(touchPos), hitInfo.collider.transform.position);
if (hitInfo.collider != null)
{
Debug.Log(hitInfo.collider.gameObject.name);
}
return null;
}
I am using this script and it tends to cast a ray to the center of screen and not on the sprite i am clicking. How can i make the script cast a ray from touch position to the sprite i clicked on??
Comment
Best Answer
Answer by bhavinbhai2707 · Mar 09, 2018 at 06:29 PM
The only mistake i made was that i forgot to change the camera to orthographic.
if (Input.GetMouseButtonUp(0))
{
Vector2 rayPos = new Vector2(Camera.main.ScreenToWorldPoint(Input.mousePosition).x, Camera.main.ScreenToWorldPoint(Input.mousePosition).y);
hit = Physics2D.Raycast(rayPos, Vector2.zero, 0);
Debug.DrawRay(ray.origin, ray.direction * 20f, Color.red);
if (hit.collider != null)
{
Debug.Log(hit.collider.name);
}
}
This is the final code i came up with and now it works like a charm :)
Your answer
![](https://koobas.hobune.stream/wayback/20220612154122im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Strange Raycast problem 0 Answers
Scripting Errors 1 Answer
Raycast not detected on instantiated object 0 Answers