I want my enemy to see me when no colliders are in the way. How do i achieve this? Im thinking maybe i need to use raycasting, but how?
My enemy is a 3d model which walks around my scene, in a house. As the player, you need to avoid getting spotted, by sneaking around. I want the enemy to spot you if he is pointing your direction, but only if no colliders are in the way (walls, etc).
Off the top of my head: Have a cube (or any gameobject) with no renderer, and a box collider attached to your enemy as a child. Then have a script attached to the cube that has something like
function OnTriggerEnter(other : Collider){
if (other.gameobject.tag == "player"){
if (allow == true){
attack();
}
}
function OnTriggerStay(other : Collider){
if (other.gameObject.tag == "wall"){
allow = false;
}else{
if (other.gameObject.tag != "wall"){
allow = true;
}
}
}
function attack(){
//do whatever is supposed to happen when the player is seen
}
Note: the attack function will keep on going, so you will need to add something to have it stop when you want it to. This isn’t tested so if it doesn’t work, play around with it. The point is that the attack function will only engage when there isn’t a wall
Now a disclaimer, there are multiple ways to do this, especially with raycasting, but I like this approach because you can easily change the enemy’s sightline by changing the child gameobject.
in the enemy’s update() method, fire a ray using transform.forward for the direction (assuming this is direction the enemy is looking)
if it hits, check to see if WHAT you hit is the player (variety of ways to do this; tags, layers, flags in script, etc etc)
This is basic raycasting.
EDIT: Here is some basic code assuming the player is tagged as “player”:
public void Update() {
RaycastHit hit;
if(Physics.Raycast(transform.position, transform.forward, 50f, out hit)) {
if(hit.transform.gameObject.tag = "player") {
// I see the player. RAAAAARRR do stuff to him.
}
}
}
NOTE: This is from memory I may have gotten the signature for Raycast incorrect, but it is the general idea. This is the update method for the enemy.