- Home /
Raycast Vision
Hello,
I have made a script that allows a Enemy to find a player thats within a circle around it then chase the player until it enters its Range which is a float of 15. It works very smoothly but has one big problem. If the players standing behind a wall or tree then the enemy can attack through it.
I had an idea that the Enemy could use raycast for vision and if it can see the player clearly then it will attack. If the player is behind a wall then the Enemy would find the closest way around it and simply run around.
Anyways I am really bad at raycast and It would be really helpful if someone could just give me a script to get me started.
Answer by Hyperion · Mar 06, 2013 at 06:21 AM
Well here's a basic raycast you could modify:
Javascript:
function Update () {
var fwd = transform.TransformDirection (Vector3.forward);
if (Physics.Raycast (transform.position, fwd, 10)) {
print ("There is something in front of the object!");
}
}
C#:
using UnityEngine;
using System.Collections;
public class example : MonoBehaviour {
void Update() {
Vector3 fwd = transform.TransformDirection(Vector3.forward);
if (Physics.Raycast(transform.position, fwd, 10))
print("There is something in front of the object!");
}
}
Then you could make the raycast check for the object by doing (Javascript)
if (Physics.Raycast (transform.position,hitinfo,fwd, 10)) {
if (hitinfo.transform.tag == "Player")
{
//do attack
}
}
No problem. Could you please thumbs up my answer? Thanks! I hope I can be of more help in the future.
I actually see a problem. I get : No appropriate version of 'UnityEngine.Physics.Raycast' for the argument list '(UnityEngine.Vector3, UnityEngine.Transform, UnityEngine.Vector3, int)' was found.
Is hitinfo supposed to be a RaycastHit or a Transform?
HitInfo is a RaycastHit. For example (are you using Javascript or C#?):
var hitInfo: RaycastHit = new RaycastHit();
or RaycastHit hitInfo = new RaycastHit();
Answer by Chronos-L · Mar 06, 2013 at 05:42 AM
Unity's Documentation On Raycast, it has a few examples that you can use to get started.
You may also need to look at Raycast Layer Mask for more advance raycast behaviour.
Your answer
Follow this Question
Related Questions
Make Particles block Raycasts/Linecasts 1 Answer
Finding RayCastHit's Origin Position 2 Answers
Implementing BUG2 algorithm 0 Answers
AI Field of vision 1 Answer
Using box collider to determine if AI should stop help 1 Answer