TL;DR:
Time = Distance / Speed
but with Unity3D’s time and distance units, it not as easy as with, say Miles as distance and MPH aas speed.
How does one calculate Time of Impact based on Distance and Speed?
EDIT: Multiplying the Speed by 50 seems to do the job though.
I am currently scripting projectile behavior. I instantiate a bullet prefab when a weapon is fired, and the bullet has it’s own script and is given some information like how fast it should travel, what it’s target is, if it should hit the target, damage, and so on.
It is for a turn-based RPG, so there will seldom be more than 10 bullets at once in the scene.
If the bullet reaches the target’s position, it should damage if it and also be destroyed.
Otherwise, it should travel a until it’s “life timer” runs out, and then be destroyed (simulating stray shots).
I hafve tried to do it via collision, but it was too unreliable, the bullet didn’t always register the target’s collider and so on.
Now I am opting for a more reliable approach: Just tell the bullet when it would reach the target based on the distance to target, bullet speed. If the time threshold is reached, it knows it is at the target’s position and should cause damage etc.
EDIT: Code Snippet:
var t : float;
var Speed : float = 0.5;
var Target : GameObject;
var Move : boolean = true;
var ImpactTime : float;
ImpactTime = Vector3.Distance(transform.position, Target.transform.position) / (Speed * 50);
function FixedUpdate()
{
if(Move == true)
{
transform.Translate( Vector3.forward * Speed, Space.Self );
}
t += Time.deltaTime;
if(t > ImpactTime)
{
//Deal damage to target, not relevatn for this example
Destroy (gameObject);
}
}