Try to Intercept Object A with Object B, when Calculating Arrive-time and Probable Location in Object A I show something to Know calculation data. But calculate position is not work properly best to see the Gif Below (Green One is object A and Red in Object B, the Grey is Calculated position that object A should look and shoot)
(As see the Gray Object is Not go Smoothly it’s get back to Red Position repeatedly):
This is the Code for Intercept:
public GameObject Enemy;
public GameObject GhostObject;//Grey Object That Show Calculating Position
Rigidbody enemyRig;
Transform enemyPos;
Vector3 bulletSpeed = Vector3.forward * 0.08f;
Vector3 current;
Vector3 last;
float time;
Vector3 enemyVel;
// Use this for initialization
void Start ()
{
enemyPos = Enemy.transform;
enemyRig = Enemy.GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update ()
{
enemyVel = CalEnemyVel();
Vector3 targetPos = enemyPos.position;
Vector3 Vr = enemyVel - transform.forward * 10f;
Vector3 Sr = targetPos - transform.position;
time = Sr.magnitude / Vr.magnitude;
Vector3 lookpos = targetPos + (enemyVel * time);
transform.LookAt(lookpos);
GhostObject.transform.position = lookpos;
}
Vector3 CalEnemyVel()
{
Vector3 vel;
current = enemyPos.position;
if (last != null)
{
vel = ((current - last) / Time.deltaTime);
}
else vel = Vector3.zero;
last = current;
return vel;
}
Movement Method for Red
public float speed = 0.5f;
void Update ()
{
float h = Input.GetAxis("Horizontal");
//GetComponent<Rigidbody>().MovePosition(transform.position + Vector3.left * h * speed);
transform.Translate(Vector3.left * h * speed);
}