Calculate Projectile Distance Travelled

Hey

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

     void Start () {
           startTime=Time.time;
     }
     void Update () {
           realTime = Time.time - startTime;
     }

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?

Thanks!

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.

private Vector3 lastPosition;
private float distanceTraveled;

private void Update()
{
    distanceTraveled += Vector3.Distance(transform.position, lastPosition);
    lastPosition = transform.position;
}
1 Like

Unfortunately that doesn’t work either, when hitting a target 1m away, or even 1000m away, it just shows values between 1400 to 1500

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”.)

–Eric

2 Likes

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;
    }
}

It definitely works. You’re doing something different in your code.

–Eric

1 Like

I can confirm that! It works perfectly fine for me as well. Many thanks @Dameon_