- Home /
Issue with raycasting in 2D
I'm working on something where I can connect circles with the same color. I'm using Physics2D.Raycast to check whether or not my finger is over a circle, and if yes, start from there, and I can drag my fingers around over other circles with the same color and a line will be drawn in between the two circles.
However, there are situations where the ray cast would not work as intended. For example, I have this situation below.
I start from the top and swipe down ward. The intentional line is to be drawn between the 3 circles in the vertical direction. But what I get is the black lines drawn. I debugged it, and as I am dragging my finger down from the 2nd circle to the 3rd, I get a log saying that the right side circle has been hit with the raycast (some times it gives a circle that isnt even near where my finger was). This issue doesnt occur in the unity editor, only on my android. The code that I am using to raycast to the circle is the following.
#if (UNITY_IPHONE && !UNITY_EDITOR) || (UNITY_ANDROID&& !UNITY_EDITOR)
hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position), Input.GetTouch(0).position);
#endif
and I am using a 2D circle colliders on the dot so that it barely covers the boundary of the circle. Does anyone see anything wrong or have a clue on what might be happening? Any help would be appreciated!
Answer by HarshadK · Aug 21, 2015 at 09:21 AM
Use Camera.ScreenPointToRay to create a ray and pass its origin and direction to your Physics2D.Raycast method.
Something like:
Ray ray = Camera.main.ScreenPointToRay(Input.GetTouch(0).position);
hit = Physics2D.Raycast(ray.origin, ray.direction);
@Harshad$$anonymous$$ Thanks for the reply. I'll have to play around with it to see if is still occuring but I wanted to ask. Is my method I am using not a good way to use? I'm new to Unity so I'm always skeptical about whether or not I am using things correctly.
In your current method your raycast is originating at the world position of your touch and its direction is a value which is the position of touch. The direction value is actually not pointing forward from the camera which is why you are getting quirky selections.
After playing around for a while, it seems to be working. Thank you very much!
Your answer
Follow this Question
Related Questions
Upon shooting, Raycast target moves infinitely 1 Answer
How to make a simple line of sight in a 2D top down shooter. 3 Answers
Button blocking raycast 3 Answers
Getting a Raycast rope to follow its object 0 Answers
Multiple Cars not working 1 Answer