- Home /
Physics.Raycast AI problem
function Update () { var hit : RaycastHit; var inSight = false var playerRelativPos =myTransform.position - target.position; if(Physics.Raycast(transform.position , playerRelativPos, hit, 1)) { if(hit.transform == GameObject.FindWithTag("Player")) { inSight = true; } what is wrong in this raycast function? it is not changing the car insight on true... I need all of the help i can get!!!
Answer by Loius · Oct 17, 2010 at 03:29 PM
You're raycasting backwards; you want
playerRelativePos = target.position - myTransform.position;
Use the 101-010 button with code selected to format it so people can read it.
It's more efficient to test if ( hit.transform == target ) than to use a Find function in an Update loop.
Thanks for the tip, but it is not working! here is the whole script I use as an AI:
var target : Transform; var moveSpeed = 3; var rotationSpeed = 3; var hunt : boolean = false; var myTransform : Transform; var distance : int; var hit : RaycastHit; var inSight : boolean = false;
function Awake() { myTransform = transform; }
function Start() { target = GameObject.FindWithTag("Player").transform;
}
function Update () {
dist = (transform.position - target.position).magnitude;
if(dist < distance){
hunt = true;
}
else{
hunt = false;
}
var playerRelativPos =target.position - myTransform.position;
if(Physics.Raycast(transform.position , playerRelativPos, hit, 1)) {
if(hit.transform ==target) {
inSight = true;
}
}
if(hunt == true && inSight == true){
myTransform.rotation = Quaternion.Slerp(myTransform.rotation,
Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed*Time.deltaTime);
myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
}
}
Your answer
Follow this Question
Related Questions
Raycast problems in my AI 1 Answer
Physics.Raycast 2 Answers
AI Raycast movement and direction 1 Answer