- Home /
Raycast2D weirdness
Hi, I'm having some trouble with Raycast2D. I loaded a project with the 2D presets. The 2D box collider and the objects defining the raycast are all on the same depth (though this shouldn't be necessary with Raycast2D... I use debug.drawline and tell it draw red on RaycastHit2D and green when the ray hits nothing. Then I circle the origin of the ray/debug.drawline in an expanding circle. Anyone got any idea what the hell is going on here?
void FixedUpdate () {
RaycastHit2D hitInfo1 = Physics2D.Raycast(player.transform.position, pointer.transform.position);
RaycastHit hitInfo2;
RaycastHit hitInfo3;
if (hitInfo1 != false)
//Physics2D.Raycast (ray1, out hitInfo1, Mathf.Infinity)) {
{ Debug.Log ("hit!" + hitInfo1.collider.collider2D.gameObject.name);
Debug.DrawLine (player.transform.position, pointer.transform.position, Color.red, 30, false);
}
else {
Debug.Log ("nohit!");
Debug.DrawLine (player.transform.position, pointer.transform.position, Color.green, 30, false);
}
}
![alt text][2] ![alt text][1] [2]:/storage/temp/21498-sample.png [1]:/storage/temp/21500-sample2.png
Answer by robertbu · Feb 01, 2014 at 04:12 AM
A Raycast uses a position and a direction. You are using two positions in your Raycast(). You can change it to:
RaycastHit2D hitInfo1 = Physics2D.Raycast(player.transform.position, pointer.transform.position - player.transform.position);
Alternately, you can change from using Physics2d.Raycast() to Physics2d.Linecast().
Huh. I figured transform.position of the pointer would provide direction by itself. Thanks for the info! I feel stupid now. Have to review those vector math primers.
I don't know how I got here, but this was exactly what I was looking for, amazing! :D