- Home /
Raycasting and enemies ai
Im trying to script my enemies ai so that when it gets within attacking range of a player placed barrier then it will start to attack. I think I need to use raycast for this. If someone could point me toward a tutorial that would be very helpfull thank you everyone.
Answer by timsk · Oct 06, 2011 at 12:01 PM
You mention raycasting in your question, but another way to do it would be to simply check the distance between the 2 objects, if its above the enemies attack range, move towards the barrier, if not start attacking. Something like this would work:
distance = Vector3.Distance(transform.position, barrier.transform.position);
//checks the distance between the 2 objects given in the paranthesis
if(distance>=range)
{
MoveTowards();
RotateTowards();
}
else
{
AttackBarrier();
}
Hope this helps :).
Also, i hope someone posts an answer using raycasting, would be interesting to see.
Well i got this in the script but its not working properly. The monster moves toword your charachter but when he is in range he dosnt start to attack.
thats probably a problem with your attack function. Post a seperate question for it.
Answer by Owen-Reynolds · Oct 06, 2011 at 03:54 PM
You pretty much always want to use distance, above, to check whether you attack. There are two more things you may want to check:
1) Is the target within my "view cone"? - can we see things behind us. Check using Quaternion.Angle
2) Do I have a clear line of sight to it? - it's nearby and in front of me, but a giant wall is between us. This is what rayCasting is used for.
Raycasting isn't difficult, but has some tricks. For example, you have to be sure to look from your eyes to the target -- not from your feet. It you want to see partially blocked targets, you need two (or more) raycasts "can I see his left side? No, well can I see his right side? No, well can I see his head?" Your friends also block your view, so when Bob ahead of you shouts kill and starts running, you say "huh -- I don't see anything." You can use layers to see through friends.
Ok sorry i didnt mention this but its 2D but this should really help me visualize it and can you point me twords a tut for raycast scripting
Characters in 2D games still have eyes- only the player has the 'God's eye view' thing happening.
(except when the characters don't have eyes. Because they're weird slimes or something)
...well when you mention it the main enemies are you guessed it SLI$$anonymous$$ES
Well, I guess they still have a sense of smell? Huh. Well that shoots my analogy down...
Your answer
Follow this Question
Related Questions
AI Raycast problem 1 Answer
Raycasting crashing Unity? 3 Answers
Problem with Unity Ray Trace AI Detect Player 0 Answers
Another Raycast Issue. 0 Answers
Finding RayCastHit's Origin Position 2 Answers