- Home /
Add object on trigger to array, then cast a ray at all objects in the array
As a part of my AI script, i want a bad-guy to target NPC civillians within range, then, if the bad-guy can see the civillians, open fire on them.
Basicly, my baddie has a sphere collider (set to isTrigger) which is quite large and detects when a civilian NPC passes into it. At this point, i'm trying to add that civilian to an array then point a raycast at it.
What's happening, is that whenever a civilian enters the 'trigger zone', a raycast is created, but it points in a seemingly random direction and only one raycast is being created at a time.
When i can do this, i'll mess with the behaviour of the Raycast, but right now i just want a raycast pointing in the direction of every civilian who comes in range.
Help?
var target : GameObject;
var newCiv;
function OnTriggerEnter (targets : Collider) {
if (targets.tag == "civilian"){
print ("civilian In Range");
newCiv = targets.gameObject;
print(newCiv);
}
}
function Update () {
civPos = newCiv.gameObject.transform.position;
var civTargets = new Array();
civTargets.Add(civPos);
print(civTargets.length);
var hit : RaycastHit;
for (i=0; i <= civTargets.length; i ++){
Debug.DrawRay(transform.position, civPos, Color.green);
if (Physics.Raycast(transform.position, civPos, hit))
{
Debug.Log("Targeting Civilian");
}
}
}
Thanks as always, Tom :)
raycast takes 2 arguments
origin and direction you have the origin correct thats your position the direction is messed up
the direction is not the end point it is the slope of the line that connects the 2 end points.
ray.origin = enemy.position
ray.direction = civilian.transform.position - enemy.transform.postion
that'll give you what you want.
Thanks sparkzbarca!Your wonderful brain has bested my ignorance...and quite right too!
Feel free to post this as an answer so can mark it as correct :)
Im still having problems with the array, but seeing as you've solved the raycast portion of this problem, i'll post that part as another question.
Thanks again,
$$anonymous$$ :)
Your answer
Follow this Question
Related Questions
onTrigger spawn object C# 3 Answers
Raycast cycle problem? 0 Answers
Raycast and OnTriggerEnter performance 1 Answer
For loop to index array storing hundreds of duplicate entries 1 Answer