I have a script to make my enemy simply follow the player
var rotationSpeed = 3; //speed of turning
var myTransform : Transform; //current transform data of this enemy
var target : Transform; //the enemy's target
var moveSpeed = 5;
function Awake()
{
myTransform = transform; //cache transform data for easy access/preformance
}
function Start()
{
target = GameObject.FindWithTag("Player").transform; //target the player
}
function Update () {
//rotate to look at the player
myTransform.rotation = Quaternion.Slerp(myTransform.rotation,
Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed*Time.deltaTime);
//move towards the player
myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
}
However i’ve spent ages trying to work out how i can make it so that when the enemy is visible to the player the enemy stops moving. I’ve looked into raycasting etc but can’t seem to get it right. If someone could write a script that somehow changes the move speed variable to 0 when the enemy is visible to the player i would greatly appreciate it , Thanks =D
You’re on the right track. You’ll want to use a raycast that zips from the badguy’s position to the player’s position and see what is returned by the raycast. If its the player, then there’s nothing in between to obstruct visibility.
Link below to show you how this is done.
You’ll also want to find ways to only do these raycast checks only when the two are within a certain a reasonable distance first. Otherwise enemies will always stand still if there’s nothing standing between themselves and the player.
Note: Raycast is a method to detect COLLIDERS, not gameobjects. Therefore, this is only going to work if you’re working with colliders on your characters.
Just raycast from the player to the enemy, if the raycast is successful then calculate the angle between the forward of the player and the ray you used for the raycast.
If this angle falls between a certain threshold (something like ±45 degrees) then the player can see the enemy.
To calculate the angle use Mathf.Atan2(), check on wikipedia how this function works