- Home /
Predict Collision with Angle
I world like to make a shooter that shoots bullets, and I have an object moving in one direction in the known velocity and I also know the speed of my bullet, it just want to make sure that they will collide to each other, I want to return a Angle I should aim.
Any help will be appreciated.
Essentially you want an autoaim that leads the target if I'm understanding this correctly? I'm assu$$anonymous$$g the bullet is moving far faster than the target? That being the case you can do this quick and messy by calculating the time it would take for the bullet to reach the current position of the target, then translate the target position by the distance it would move in that time and that will be the approximate position the target will be when the bullet arrives. Then just calculate the angle from that translated target position to your firing position. It's not perfect, but if the difference in velocity is quite high then the error will be insignificantly small. To do it absolutely accurately would take a bit more maths. I'll have a think and comment again.
private Vector3 $$anonymous$$Target(Vector3 firePos, Vector3 targetPos, Vector3 targetVel, float bulletSpeed)
{
float distanceToTarget = Vector3.Distance(firePos, targetPos);
float bulletTime = distanceToTarget / bulletSpeed;
Vector3 targetProjectedPos = targetPos + (targetVel * bulletTime);
return (targetProjectedPos - firePos).normalized;
}
That should be the quick and nasty version, it returns a direction vector, the two angles can be calculated from that if need be. I think to get it bang on you have to take the distance from the current target position and the projected target position, take the difference of those, square root it, divide by the bullet speed and add that to the time, then recalculate the projected position with the adjusted time. I'm testing that atm.
Your answer
![](https://koobas.hobune.stream/wayback/20220612234840im_/https://answers.unity.com/themes/thub/images/avi.jpg)