- Home /
RaycastHit2D is not precise when casting a ray to a box collider 2d
I am a beginner at unity so bare with me, so when i use a raycasthit2d on a box collider 2d, the raycast activates sometimes outside of the box collider which seems odd and it sometimes does not activate in the box collider. i use debug.drawline to cast a ray to indicate where my ray lands on.
RaycastHit2D collide = Physics2D.Raycast(main.transform.position, Input.GetTouch(i). Debug.Log(collide.collider);
main is the main camera in the scene.
If you are going to raycast using world space AND screen space, you should convert the screen space to world space using Camera.ScreenToWorldPoint(Input.GetTouch(i))
Vector2 hit = Camera.main.ScreenToWorldPoint(Input.GetTouch(i).position); RaycastHit2D collide = Physics2D.Raycast(hit, Input.GetTouch(i).position);
Like this?
No, something like this....
RaycastHit2D collide = Physics2D.Raycast(main.transform.position, Camera.ScreenToWorldPoint(Input.GetTouch(i));
I believe you are raycasting in wrong direction.
RaycastHit2D collide = Physics2D.Raycast(main.transform.position, Camera.main.ScreenToWorldPoint(Input.GetTouch(i).position));
this will raycast from your camera position to your touch position. The difference is, the ray will not go below your finger ray will be in the X-Y plane and not in Y-Z plane.
try
origin = Camera.main.ScreenToWorldPoint(Input.GetTouch(i).position);
direction = Vector3.zero
Physics2D.Raycast( origin, direction );
you can also debug it by debug.drawline ( origin, (origin+Vector3.forward*100)); Also, the camera must be orthographic.
I did the changes so now it is exactly like u have mentioned, however nothing has changed it still return null. I included the debug.drawline, but it did not draw a line for me. Thanks for helping too :D
Well, that is odd, debug.drawline will draw in Scene window just to make sure you are not looking in game view. What is the rotation of your camera? I assumed it is facing positive Z direction.
Your answer
![](https://koobas.hobune.stream/wayback/20220612162441im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How can I get my BoxCollider2D to stay centered on my sprite? 2 Answers
Collision Detection + Transform Offset Question 0 Answers
Inaccurency BoxCast2D,Inaccuracy BoxCast2D 0 Answers
2D grab script collider problems 0 Answers
BoxCollider2D only registers clicks in top right quarter of its region 0 Answers