- Home /
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.
Answer by chearner · Aug 04, 2010 at 02:41 AM
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))
{
play an alert sound;
}
Answer by Ricardo · Aug 01, 2010 at 08:58 AM
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:
- The nearest approach time between that neighbor and the one we care about (the player in your case) based on their speeds.
- Evaluating only those that fall within our arbitrary minimum collision time threshold.
- Calculating the nearest approach position for both on that time window.
- 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.
Answer by qJake · Aug 01, 2010 at 07:24 AM
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).
Your answer
Follow this Question
Related Questions
Determining rotation for collision avoidance? 3 Answers
Help with kinematic NPCs following non-Kinematic player and avoiding obstacles 0 Answers
How to combine NavMesh Agent with Character Controller 0 Answers
the most efficient way to detect colision between objects in a large scene (Strategy Game) 1 Answer
move till collision 1 Answer