I’m looking for a way to calculate how far a projectile has travelled after it has been instantiated, and until it collides and is destroyed. Atm i’m using a basic equation, distance = velocity * time, where velocity is the muzzle velocity of the projectile. The problem i’m facing is calculating the time the projectile has been alive. I’ve tried stuff like
As well as with different kinds of Time, they seem to work, but when standing still and shooting they all give different results (can range from a lot), e.g. standing 10m away from a target, and hitting it, the time can be quite high.
Does anyone know if there’s a proper way to determine how long the projectile was alive and how far it has actually travelled in meters?
Just keep track of the position last frame. Add the distance between that and the current position to a running count, and you have your distance traveled.
It should be in FixedUpdate instead of Update, since you’re presumably using physics, but aside from that it would work fine. (Well, also there should be a Start function that does “lastPosition = transform.position”.)
Unfortunately that doesn’t seem to be working either, although it’s somewhat more accurate, it gives results in multiples of 8, so it only reports 0, 8, 16, 32, etc…
Don’t know what you are doing with the distance, but hopefully this should help.
using UnityEngine;
using System.Collections;
public class Foo : MonoBehaviour {
// Instantiated position
private Vector3 instPos;
private float instTime;
// Called when instantiated by default
// Also will be called when script is enabled, helps when pooling
private void OnEnable ()
{
instPos = transform.position;
instTime = Time.time;
}
// Called when destroyed by default
private void OnDisable ()
{
float dist = Vector3.Distance (instPos, transform.position);
float timeDiff = Time.time - instTime;
}
}