- Home /
Enable renderer when in line of sight
Hi, I'm currently trying to pull off enabling a renderer of an object when it's in line of sight of the object. I wouldn't really know how to pull this off. I've tried Raycasting which still seems like the most plausible salution, but I can't get it to cast in a 360 radius. Does anyone encountered the same problem before?
Example: Left: Blue square is the player, enemy currently not visible. Right: Enemy is now visible.
Answer by whydoidoit · Feb 17, 2014 at 04:52 PM
You shouldn't need to cast 360 - just cast from the player's position to the enemy's position and see if you get there (hit the enemy, not something else first).
If you want to limit it so that the player is actually pointing in the right direction, get the vector to the enemy:
var vectorToEnemy = (enemy.transform.position - player.transform.position);
And check if the angle between it and the player's forward is within range:
if(Vector3.Angle(vectorToEnemy.normalized, transform.forward) < 80) {
Enemy is visible
}
Yes that's it. Work out a range if necessary, then apply the basic "in the viewing area" check as described in the comment, then cast a ray and find out what it hits. If it's the enemy then you can see it.
RaycastHit hit;
if(Physics.Raycast(transform.position, vectorToEnemy, out hit, vectorToEnemy.magnitude)) {
if(hit.collider.gameObject == enemy.gameObject) {
//I can see you
}
}
I often do it the other way around to avoid the loop - so each enemy casts towards the player if they are in range and the player is facing them. It's a matter of choice though.
You are using a raycast, the second parameter is not a position, it's a vector from the start of the ray. You can use Linecast if you want to use two positions - but I was going the raycast route so you could check for viewing angle, when you need the vector anyway.
Answer by NickP_2 · Feb 17, 2014 at 04:56 PM
Use a raycast as following:
orgin: one of the 2 squares, the square u didnt chose shall be named "othersquare". Now the direction will be: othersquare.transform.position - transform.position.
Now just do a Physics.raycast check, if thr raycast returns anothet object than the othersquare, disable the renderer!
Ps: sorry i coulnd write the code im on my train back home, typing on my phone