I'm working on a lock on function and so far I can lock on to the nearest enemy, but my player can't move around the enemy, i can only move towards it. I have my project setup so that the camera is always at a fixed position/rotation, and the player moves independently of the camera.
Here's my move function:
public void Move(float h, float v) {
if (!lockPlayerMovement) {
Speed = 0;
MoveDirection.y -= Gravity * Time.deltaTime;
if (Mathf.Abs(v) > ThumbStickDeadZone || (Mathf.Abs(h) > ThumbStickDeadZone)) {
var lookRotation = new Vector3();
lookRotation.Set(h, 0, v);
lookRotation = lookRotation.normalized;
var rotation = Quaternion.LookRotation(lookRotation, Vector3.up);
if (lookRotation.magnitude > ThumbStickDeadZone) {
Speed = RunSpeed;
transform.rotation = Quaternion.Slerp(Transform.rotation, rotation, Time.deltaTime * TurnSpeed);
}
}
if (Controller.isGrounded) {
MoveDirection = Transform.TransformDirection(Vector3.forward).normalized;
MoveDirection *= Speed * Time.deltaTime;
//if (Input.GetButton("Fire1"))
// MovementProperties.MoveDirection.y = JumpSpeed;
}
Controller.Move(MoveDirection);
}
}
Lock On Function:
void Update () {
playerPosition = transform;
if (enemyLockedOn && enemyTarget != null) {
transform.LookAt(enemyTarget.transform);
}
}
void ScanForEnemies() {
int numOfEnemies = 0;
float distanceFromPlayer;
GameObject closestEnemy;
List<GameObject> enemies = new List<GameObject>();
Collider[] cols = Physics.OverlapSphere(transform.position, radius);
foreach (Collider col in cols) {
if (col && col.tag == "Enemy") {
++numOfEnemies;
enemies.Add(col.gameObject);
//print(Vector3.Distance(playerPosition.position, col.transform.position));
}
}
if (enemies.Count > 0) {
distanceFromPlayer = Vector3.Distance(playerPosition.position, enemies[0].transform.position);
closestEnemy = enemies[0];
for (int i = 0; i < enemies.Count; i++) {
if (Vector3.Distance(playerPosition.position, enemies[i].transform.position) < distanceFromPlayer) {
distanceFromPlayer = Vector3.Distance(playerPosition.position, enemies[i].transform.position);
closestEnemy = enemies[i];
}
}
/* Set closest enemy as the player target and lock player to that enemy (while in range -- or scan pressed again) */
enemyTarget = closestEnemy;
if (enemyTarget != null) enemyLockedOn = true;
print("Closest Enemy : " + closestEnemy + " | Distance From Player : " + distanceFromPlayer);
print("Number of nearest enemies : " + numOfEnemies);
}
}