I am creating a small application where I have some cars driving around in a top-down view environment, and I am trying to give them some AI so they will brake if they are about to hit another car. At first I had some problems getting the Raycast to not hit itself, but eventually I got it working. However, now it won’t react to other cars. I am using a prefab that clones up the same car every X seconds but they don’t seem to notice eachother. The code I am using to notice the cars are the following:
function Update ()
{
somethingSpotted = Physics2D.Raycast(Vector2(rigidbody2D.transform.position.x,rigidbody2D.transform.position.y-1.2),Vector2(0.5,-4.5));
Debug.DrawLine(Vector2(rigidbody2D.transform.position.x,rigidbody2D.transform.position.y-1.2),Vector2(0.5,-4.5),Color.blue);
if (somethingSpotted == true)
{
Debug.Log("Car spotted");
rigidbody2D.velocity = new Vector2(0,0);
}
}
Something spotted is a boolean that is false by default. I have a prefab for the car model with both a box collider and a rigidbody2D. But the Raycast never seems to be true and I can’t figure out why.
PS: The Vector2 is set to one of the cars spawn points for debugging purposes.
What jumps out at me is that you’re using the same parameters for Raycast as DrawLine, but they function differently. Raycast wants start (world), direction (local), and distance (assumed infinite). DrawLine wants start (world) and end (world). Your Raycast isn’t going where your DrawLine is going. Maybe you should be using Physics2D.Linecast?
That could be a good idea. Or I could change it to raycast Thanks for the reply. Also, is there a way to create a Debug that is equivalent to Raycast? I’d prefer to use direction/distance rather than a start/end point
One other thing: Physics2D.Raycast does not return a boolean value, it returns an instance of RaycastHit2D which by the way always returns a non-null value. So, in order to check if your ray cast hit something, you have to test if hit.collider is not null. Please note that the code snippet in the documentation is not correct and misleading, and it would be nice if it was updated sometime soon.
…Which BTW can be implicitly cast to a Boolean, internally checking whether or not there’s a hit. Seems more robust than checking the collider, given that the implementation already doesn’t match the documentation.