Hi, I’m trying to make an enemy tank approach the player when it’s within a certain range and then reverse back to where it was and then approach the player’s position again and repeat in a loop until it’s destroyed or the player is out of range. I find I can get it back to it’s initial position easily enough using transform.position = tankPos; after I declare tankPos as a private vector3, but it’s sort of teleporting the enemy and it’s not what I want.
The problem is if I use transform.Translate (Vector3.back * moveSpeed * Time.deltaTime); the tank begins going backwards but then locks into a position because the
if (playerDistance < 80f) {
chase ();
}
is now getting called!
If anyone can give me any advice about a technique that might work that would be great.
I’ve also tried using fixed joints and spring joints and the results weren’t so good.
using UnityEngine;
using System.Collections;
public class TankScript : MonoBehaviour {
public Transform player;
public float playerDistance;
public float rotationDamping;
public float moveSpeed;
public static bool isPlayerAlive = true;
//public float speed;
public Rigidbody tankBull;
public float speed = 20;
public Transform spawnPoint;
public float elapsedTime = 0.0f;
public float shootRate = 3.0f;
public float lastFireTime;
public float fireDelay;
private float time;
GameObject MockronBossFour;
float lockPos = 0;
private Vector3 tankPos;
void Start () {
MockronBossFour = GameObject.Find ( "MockronBossFour" );
MockronBossFour.transform.rotation = Quaternion.Euler(transform.rotation.eulerAngles.x, lockPos, transform.rotation.eulerAngles.z);
tankPos = transform.position;
}
void Update () {
if (isPlayerAlive) {
playerDistance = Vector3.Distance (player.position, transform.position);
if (playerDistance < 80f) {
lookAtPlayer ();
}
}
if (playerDistance < 80f) {
chase ();
}
if (playerDistance < 10f) {
back ();
}
}
void lookAtPlayer()
{
Quaternion rotation = Quaternion.LookRotation (player.position - transform.position);
transform.rotation = Quaternion.Slerp (transform.rotation, rotation, Time.deltaTime * rotationDamping);
}
void chase ()
{
transform.Translate (Vector3.forward * moveSpeed * Time.deltaTime);
}
void back (){
transform.Translate (Vector3.back * moveSpeed * Time.deltaTime);
transform.position = tankPos;
}
