Hello everyone.
I’m trying to understand raycasting, and the script reference isn’t really making sense to me for what I’m trying to do.
This is the scene. It’s a 2d plane:
T X P T
T= Towers, the objective to reach.
X= Melee bad guy
P= Player’s created character
How do I have the X check if there is something a few feet ahead. If there isn’t, I’ll make him move. If there is he will preform an attack function.
Should I use Raycasting? I’m just confused as to how I should go about doing that.
I think I would use a trigger that follows the bad guy. Theres lots of info on triggers on both the forum and in the documentation.
//perlohmann
Raycasting is exactly what you want in that situation; it’s what it is for:
function Update ()
{
var fwd = transform.TransformDirection(Vector3.forward);
if (Physics.Raycast (transform.position, fwd, 10))
{
print ("There is something in front of the object!");
}
}
You could use OverlapSphere to check if in the neighborhood of X there’s something he needs to be aware of (in a certain radius); ie the player.
If there is, perform the attack function.
If there is not, call a function that makes him move in a random direction.
But this works even if the player is behind the enemy (where theoretically X shouldn’t be able to see the player).
So, if you want some sort of “controlled area in front of X”, so he can “look” and “understand” only things that are in front of him, you could for example use 3 raycasts, 1 in front, 1 on, say, 45° from the front, and another at -45°.
If the raycast returns something with tag “player” or whatever you want, perform the attack; else just move randomly.
Just a couple ideas.