- Home /
How does Raycast2D works? Am i doing it right? [Huge Line]
Hey there!! ^^ I did this little and simple code and in the inspector the Debug.DrawLine, Draws a huge diagonal green line ... Now, the code still returning the data from the if statement ... in other words everything works fine ... but why it does make a diagonal and so large diagonal line? Is that fine? o.O
void Update(){
if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
{
RaycastHit2D hit = Physics2D.Raycast (Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position), Vector2.zero);
if(hit.collider.tag == "//someobject"){
Debug.Log("someObjectisHitted");
Debug.DrawLine(Input.GetTouch(0).position, hit.point, Color.green, 50);
}
}
$$anonymous$$aybe you should test the Debug.DrawLine instruction using Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position) ins$$anonymous$$d of Input.GetTouch(0).position directly as the origin point.
Answer by DiegoSLTS · Oct 15, 2015 at 12:00 AM
What's the line supposed to represent? You're passing the touch position as the first parameter, that's "The position of the touch in pixel coordinates", a Vector2 that will have any value inside your phone's screen resolution.
hit.point, in the other hand is returnig a world position.
Now, Debug.DrawLine expects values in world position, it draws a line in the world from the first parameter to the second one. Your first parameter is being interperted as a world position, probably far away from your camera. So you get a line that comes from some far away point and ends in the hit point.
So, again, what's that line supposed to display? What you send as the first parameter depends on that answer.
Also, Debug.DrawLine and Physics2D.Raycast are not related in any way, the fact that DrawLine shows something weird doesn't mean you should worry about the raycast working or not, you're just drawing the line in the wrong way.
I added the line to see how Unity 3D systems vs 2D systems works nothing else a mere tests
And as the question says it works perfectly ... I just want to know Why it shows that line.
DiegoSLTS answer seems correct as to why the line is like this. $$anonymous$$y guess is that Input.GetTouch(0).position.z and hit.point.z are probably very different so it looks like the line is co$$anonymous$$g from the sky.
So as to "why is shows that line"...it's because your wrote "Debug.DrawLine(Input.GetTouch(0).position, hit.point, Color.green, 50)" in your code :-P
Your answer
![](https://koobas.hobune.stream/wayback/20220612041327im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Raycasting not working? 1 Answer
Linecast, rotate end point relative to objects rotation 1 Answer
Unity Raycast2D results are not as expected? 1 Answer
Animation is not playing all frames 0 Answers
Layer Mask on raycast2d not working? 1 Answer