Hi. I am making a game where there are guards that the player has to sneak past or dispose of them without other guards seeing the player. I was thinking of doing a raycast that looks for the player but it’s just a line. Is there a way to make a raycast that works like the view of a camera? Or is there some other way? Also ,I know this might sound like a stupid question but how do you change the animation of an object if the previous animation hasn’t finished?
This has been discussed a few times before; try searching on ‘line of sight’, ‘cone of sight’, ‘raycast cone’… you should find some helpful threads.
float distance = Vector3.Distance(this.transform.position,hero.transform.position);
if(distance < lineOfSight){ //within a close raidus then shoot out rays
Vector3 rayDirection = hero.transform.position - transform.position;
Vector3 enemyDirection = transform.TransformDirection(Vector3.forward);
float angleDot = Vector3.Dot(rayDirection,enemyDirection);
if(angleDot > 0.0){ //if facing the same direction
RaycastHit hit;
if(Physics.Raycast(transform.position,rayDirection+ new Vector3(0,3,0), out hit, 1000,targetLayer.value)){
if(hit.collider.name == “Hero”){
StartAttacking();
AlertOthers();
return;
}
}
}
}
You could also take a look at the Antares Project, which includes a demo of exactly what you’re looking for in a scene called “AntaresAIRange” or something like that. You might not want or need the other stuff that this includes, but the AIRange scripts are quite nice because they include editor scripts and a range cone/radius indicator and some other features.
edit: doesn’t seem to have the demo scene in the version for 3.0, but the scripts are still there. Not sure why, but you could always try the old version out in Unity 2 for an example of how to use it.