Turret With Raycast Camera

So I made a turret that has a sphere as a trigger and shoots at the player when he enters it, which works fine, except it also shoots at the player when hes behind walls, and I don’t want that.

I thought about making a cone shaped trigger in front of the turret kind of like a view area but the turret would still shoot at the player behind a wall if the trigger was going through it, and I don’t want to have to individually resize the trigger for each scenario.

And my final conclusion was to make a child camera of the turret that would raycast and shoot only if it hits an object with a tag “Player”.

So I have a couple questions about that.

  1. Is it a good way, or is it resource expensive?

  2. Is there a better way?

  3. How would I do it? Something like this like in the unity docs?

    function Update () {
    var hit : RaycastHit;
    if (Physics.Raycast (transform.position, -Vector3(0,0,1), hit, 100.0)) {
    var distanceToGround = hit.distance;
    }
    }

And then how would I make it react only to an object with tag and execute a function in its parent?

Raycast is really confusing to me even tho I can visualize it I don’t understand how the code works, none of the tuts on raycasting helped me, and I could never understand Unity docs. x’D

PS: Sorry for the code not being in code quotes its not working now for some reason, it does usually.

Having examined you code, I’m not sure what functionality you want. Do you want it to not track the player if the player cannot be “seen” or do you want it so not fire if the player cannot be seen? In either case, I’d recommend a Physics.LineCast():

function CanSeePlayer() : boolean {
	var hit : RaycastHit;
	
	if (Physics.Linecast(transform.position, myTarget.transform.position, hit)) {
		if (hit.collider.tag == "Player")
			return true;
		// An alternate check that does not depend on the tag
		if (hit.transform == myTarget)
			return true;
	}
	
	return false;
}

Note this only check to make sure the pivot point of the turret can see the pivot point of the player. If the player is only partly visible, this may return false. A more complete check would linecast against the corners of the either the renderer.bounds or the mesh.bounds (translated into world space).