# Collision course detection between two moving objects. Is a collision imminent?

I would like to display a warning when an object is on course to collide with the player, in this case a POV player / main camera.

Based on the trajectory of a moving object, how can I tell if it will collide with the camera so I can dispatch a warning to the player?

It would be good to have a distance measure in it so that the warning would be more urgent the closer it gets.

SpikeX suggestion for raycast solves only one part of the problem, since if both objects are moving it is perfectly possible that the raycast intersects with the player on its current position, but that does not mean there will be a collision in the future (when the player has moved).

You may want to have a look at SteerForNeighborAvoidance from UnitySteer. It calculates if a vehicle is likely to collide with another one, by estimating for each neighbor that it's aware of:

1. The nearest approach time between that neighbor and the one we care about (the player in your case) based on their speeds.
2. Evaluating only those that fall within our arbitrary minimum collision time threshold.
3. Calculating the nearest approach position for both on that time window.
4. Determining if that would be within the danger threshold (the sum of the radius of both vehicles).

If the answer to #4 is Yes, then there is a collision on the time estimated on step #1.

Could you just use Physics.Raycast, raycasting in a forward direction (`Vector3.forward`), and if the ray hits the player, the object is "facing it", so if it's moving towards it they'll collide.

Raycasts use a "length" property, so you can specify how far out it goes (so if the player's too far away it won't hit).

I found Physics.Linecast using layers to be the most effective. On the update() I scan for targets directly in front of an object adding the velocity times a multiplier. The linecasts are placed randomly around the perimeter of the object on each update.

``````RaycastHit hit;
float randomX = (1 - 2 * Random.value) * 300;
float randomY = (1 - 2 * Random.value) * 300;
Debug.DrawLine(transform.position + new Vector3(randomX, randomY, 0), transform.position + (rigidbody.velocity * 10) + new Vector3(randomX, randomY, 0), Color.red);
if (Physics.Linecast(transform.position + new Vector3(randomX, randomY, 0), transform.position + (rigidbody.velocity * 10) + new Vector3(randomX, randomY, 0), out hit, 2))
{