Hello guys. I made small island and i have 2 first person character controllers. The one is the player and the other is the enemy (i removed the camera from the enemy so when i press play, unity gives me the player). I putted a sphere trigger collider to the enemy so when i get to the “enemy area” the enemy shoots me bullets (small spheres). The problem is that i cant make the enemy face me all the time so bullets come on me, or just for the player to understand that the enemy has perceived him. Its something about rotation and the enemy forward or something like that. Can anyone help me?
You could calculate the enemy->player direction and Slerp the enemy forward to it - but the calculated direction must be strictly horizontal, or the enemy will tilt weirdly when the heights are different:
var turnSpeed: float = 5;
private var target: Transform;
function OnTriggerEnter(other: Collider){
if (other.tag == "Player"){ // player entered trigger:
target = other.transform; // make it the target
}
}
function OnTriggerExit(other: Collider){
if (other.tag == "Player"){ // player exited trigger:
target = null; // no target at sight
}
}
function Update(){
if (target){ // if target at sight...
// find the target direction:
var dir = target.position - transform.position;
dir.y = 0; // make direction strictly horizontal
dir.Normalize(); // normalize it
// turn gradually to the target each frame:
transform.forward = Vector3.Slerp(transform.forward, dir, turnSpeed * Time.deltaTime);
// your attack code may be here:
// -- attack code --
}
}
The code above may be different from what you already have - adapt the direction part to your current code, or adapt your shooting code to the script above.
EDITED: This is the C# version:
public float turnSpeed = 5;
Transform target;
void OnTriggerEnter(Collider other){
if (other.tag == "Player"){ // player entered trigger:
target = other.transform; // make it the target
}
}
void OnTriggerExit(Collider other){
if (other.tag == "Player"){ // player exited trigger:
target = null; // no target at sight
}
}
void Update(){
if (target){ // if target at sight...
// find the target direction:
Vector3 dir = target.position - transform.position;
dir.y = 0; // make direction strictly horizontal
dir.Normalize(); // normalize it
// turn gradually to the target each frame:
transform.forward = Vector3.Slerp(transform.forward, dir, turnSpeed * Time.deltaTime);
// your attack code goes here:
// -- attack code --
}
}
Notice that basically the differences are restricted to the way variables and functions are declared.