- Home /
Limit Rotation
Hi,
What would be the best way to limit this tracking rotation between 0 - 180 degrees ? I've used transform.eulerAngles to get the degrees of the transform and limited it between 0 - 180 but it stays at ether one end or the other.
Thanks.
function trackTarget(){
// Rotate towards target and track it
var targetPoint = target.position;
var targetRotation = Quaternion.LookRotation (targetPoint - transform.position, Vector3.up);
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, Time.deltaTime * trackSpeed);
if(distanceToPlayer < attackRange){
shoot();
}
}
Answer by robertbu · Jan 13, 2013 at 08:32 PM
Angle should be based off target rotation, not the transform rotation.
var angle = targetRotation.eulerAngles.y;
Note the way this code is written, the rotation will stop when the object passes beyond the range even if the Slerp rotation has not fully rotated to the limit.
P.S. How did you embed formatted code into a comment?
I'm assu$$anonymous$$g that you are looking in the positive Z direction and you are wanting to allow the player to rotate/look from 90 degrees on the left to 90 degrees on the right. If so, try this:
var angle = targetRotation.eulerAngles.y;
if (((angle >= 270.0f) && (angle <= 360.0f)) || ((angle >= 0.0f) && (angle <= 90.0f)))
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, Time.deltaTime * trackSpeed);
Note I've not verified that Quaternion.eulerAngles() always returns a positive values for x,y,z, so there may be a bit more to assure a positive angle.
Hi, Thanks for that, I tried that before but like I said the gun stays there once it's reached the limits, so once you leave the guns range and then come back into it the gun wont track again because its at one of the limits.
I tested the above code/logic and it works fine. Perhaps you need to post the not working code.
function trackTarget(){
var targetPoint = target.position;
var targetRotation = Quaternion.LookRotation (targetPoint - transform.position, Vector3.up);
angle = transform.eulerAngles.y;
if (((angle >= 270.0f) && (angle <= 360.0f)) || ((angle >= 0.0f) && (angle <= 90.0f)))
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, Time.deltaTime * trackSpeed);
if(distanceToPlayer < attackRange){
shoot();
}
}
That was easy .. ;)
transform.eulerAngles.y = $$anonymous$$athf.Clamp(transform.eulerAngles.y, 10, 170);
Your answer
Follow this Question
Related Questions
Quaternion.LookRotation only on Y axis 0 Answers
Direction of rotation 0 Answers
Quaternion Slerp 180 Away from target 1 Answer
How can I instantiate a gameobject facing another gameobject 2D? 0 Answers
My LookRotation forces my character to snap back, and face starting direction after I stop moving? 2 Answers