- Home /
Raycast target line of sight
Hello, I seem to be in a bit of a pickle with a piece of code. I am trying to get the turret to only shoot when target is in line of sight, In my tests i have a target on a path to cross a turret, in between them both is a wall, I don't want the turret to look at or even shoot at the target until its in the light of sight, Instead, My turret shoots through the wall GRR. please check this code and slap my hands on what i did wrong, Thanks.
public override void Update(){
base.Update();
if(turretObject!=null && target!=null && !stunned){
//~ if(animateTurret==_TurretAni.YAxis){
Vector3 targetPos=target.thisT.position;
targetPos.y=turretObject.position.y;
Quaternion wantedRot=Quaternion.LookRotation(targetPos-turretObject.position);
turretObject.rotation=Quaternion.Slerp(turretObject.rotation, wantedRot, 15*Time.deltaTime);
if(Quaternion.Angle(turretObject.rotation, wantedRot)<45) targetInLOS=true;
else targetInLOS=false;
//~ }
}
RaycastHit hit;
if (Physics.Raycast(thisT.position, target.thisT.position, out hit)&& hit.transform.tag == "wall")
targetInLOS=false;
print("Raycast hit: " + hit.transform.tag);
}
Answer by robertbu · Oct 01, 2013 at 10:59 PM
Your Raycast is not right. For this form of Raycast, the first two parameters are a position and a direction. You have two positions. Replace the second parameter with target.thisT.position - thisT.position; So it would look like:
if (Physics.Raycast(thisT.position, target.thisT.position - thisT.position, out hit)&& hit.transform.tag == "wall")
Note the 'target.thisT.position' looks strange. Maybe it should be 'target.position' or 'target.transform.position'?
Thanks for the hot-fix its working the way it should now, Changing "target.thisT.position" to "target.transform.position" had no effect at all. Thanks again,
P.S. Would love to up-vote but i can not as i first need 15 rep, Sorry.
Oh there is still a problem, $$anonymous$$y turret seems to look at the target through the wall, Following the target until its in LOS then shoots, so the shooting part is fixed, but the rotation part isnt,Any ideas? Thanks in advance.
You need to not update wantedRot on line 9 if targetInLOS is false. And as a $$anonymous$$or nit, your Raycast() should be done at the top of Update() so that its calculation of targetInLOS not stale.