- Home /
Lock rotation (range of motion) of auto-aiming bullet spawner
Hi, I have an auto-aiming bullet spawner attached to my Player and would like to limit its range of motion so that it cannot aim too far off to the left/right/up/down. I have come across a few techniques using Mathf.Clamp and Quaternions but cannot get this to work as it should. I am looking for say a -30 to 30 degree limit for both the X and the Y rotation. The aiming is simply achieved using a trigger ahead of the Player which detects any enemies entering and then aims at them if they are inside it.
My script simply takes in the direction of the enemy and then assigns the bullet spawner's direction to this. It then uses LookRotation to look in the direction, thus:
transform.rotation = Quaternion.LookRotation(bulletDirection);
Any help would be great. Thanks
Answer by Olgo · Nov 20, 2012 at 03:23 PM
You could use something like this...
if(target){
Vector3 dir = (target.position - _myTransform.position).normalized;
float direction = Vector3.Dot(dir, transform.forward);
dir = (target.position - _myTransform.position).normalized;
direction = Vector3.Dot(dir, transform.right);
if(direction > rotLimit){
//turn aimer left
}
else if(direction < -rotLimit){
//turn aimer right
}
else{
//do nothing
}
}
else{
//do nothing
}
Then copy the same thing for Up and Down, maybe add a distance check if you want it to have a specific range. This would keep the auto aimer tracking the target at the max of its rotation (might be good for a turret in a tower defense type game). Not sure if that's exactly what you want but it would be easily modified for other purposes.
Hi Olgo, forgive the delay in replying, have been busy working on other stuff :)
Thanks for the script, it looks like what I'm after. However, I wonder if you can clear something up for me.
Can you explain what the _myTransform variable represents? I can see that 'target' would the enemy and that the transform (object script it attached to) would be the bullet spawner, so what might this be?
_myTransform is the (cached) transform of the object this script is attached to. That way you can access _myTransform.position for use in distance calculation or for normalizing a vector between 2 points.