I’ve been writing a Tower defence game and I’ve been pretty successful with the whole target selection and the rotating and bullet collision and enemy health and all that the only problem I’ve got left is I want the turret to only start firing when it’s facing the target. At the moment as soon as the target is assigned the turret starts shooting in the wrong direction.
I don’t want to use a timer as that isn’t really accurate enough. As the difference of selecting 1 target to the next is different.
I’ve considered ray casting but as there will be multiple targets it’s possible the ray cast will hit the a different collider and start shooting to early.
Just use a raycast, if the ray hits the character then it is facing and can be shooting.
In order to avoid shooting the wrong one as you mention, use a target variable and check if the hit of the ray is the target if not then keep on rotating without shooting.
Very sorry I can’t provide any code examples as I don’t have unity to hand right now and can’t remember it off the top of my head! However the rough things you want to do are:
get the vector (call it ‘offset’) from your tower to the target (target.transform.position - tower.transform.position)
‘normalize’ the ‘offset’ value to get a new unit vector that represents the direction from your tower to the target
get the direction your tower is pointing in (I think this is tower.transform.forward)
do the dot product of the 2 directions (Vector3.Dot).
If the dot product is 1, the 2 directions are perfectly aligned and your tower is facing precisely at the target. If the dot product is -1, the 2 directions are exactly opposite and your tower is facing directly away from the target. You probably want something like ‘if dot product > 0.95’ to give it a little bit of leeway.
As a side note, in case you arent aware, that dot product is the same as taking the cosine of the angle between the 2 vectors, which is why the calculation works - cos(zero degrees) = 1, cos(180 degrees) = -1.
This is the classic way in any game of asking the question ‘is object A facing object B’, or more generally ‘is this direction similar to this other direction’ and you will probably come to know it quite well over the years