Proper movement code for calculating leading shoots

Hello Unity community.

First of all, you will probably wonder what I exactly mean with that title. I wanted to make leading shoots to fire to mobile targets so that they will hit the target even though the target was in movement, so I found this page: http://wiki.unity3d.com/index.php/Calculating_Lead_For_Projectiles and copied these code, assuming it would work.

Then, when I tested my project, I noticed it wasn’t working, the shoots where facing the target’s current position. Later I noticed that Unity was assuming that the target velocity was 0, to be precise (0.0, 0.0, 0.0), the same as if the target was standing still.

At this point, I assumed that I had done my player movement wrong, so I need to know a movement code that Unity could recognise as a proper movement so that my leading shoots will work and the target.GetComponent().velocity would be greather than 0.

Here is my code:

``````using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class PlayerController : MonoBehaviour {

public float speed;
public float rotationSpeed;

void FixedUpdate ()
{       // Rotates right and left
transform.Rotate(0, -Input.GetAxis("Horizontal")*rotationSpeed*Time.deltaTime, 0,Space.World);

if (Input.GetKey("up")||Input.GetKey("w")){ // Goes forward
transform.Translate(0,0,Time.deltaTime*speed,Space.Self);
}

if(Input.GetKey ("down")||Input.GetKey("s")){ // Goes backward
transform.Translate(0,0,-Time.deltaTime*speed,Space.Self);
}

if (Input.GetKey ("e")){ // Goes right
transform.Translate(Time.deltaTime*speed,0, 0, Space.Self);
}
if (Input.GetKey ("q")){ // Goes left
transform.Translate(-Time.deltaTime*speed,0, 0, Space.Self);
}
}
}
``````

I need to know if this code is right or, instead, a proper code that Unity could recognise as a movement (I tested the speed by writing “print(target.GetComponent().velocity)”. Could you tell me if this is right?

Hi,

Your problem is simple to resolve. Don’t use transform translate !
First put a rigdbody on your player.
Second use GetComponent().velocity = new vector3(…);

You don’t need to use Time.deltatime because velocity is update by unity with a Time.deltatime.

Say me if you don’t arrive, i’ll give you some code. But it’s better to arrive alone to progress.