我试图约束一个物体的旋转,这样它就像一个操纵杆(意味着它只能从中心旋转到某个最大角度)。
我试图限制每个轴上的旋转,但是它们在旋转时表现得非常奇怪(角度值不会线性增长)。用于提供此旋转的输入I是物理控制器的旋转。我怎么能这样做?
答案 0 :(得分:1)
It sounds to me like there are two parts to the problem:
In my code examples, I'll be assuming that the initial rotation of the virtual joystick is zero across the board (Quaternion.identity
), and that your supplied rotation is called newRotation
.
For the first part, Quaternion.Angle()
comes to mind. This gives the angle between two given rotations, and can be used like so:
if (Quaternion.Angle(Quaternion.identity, newRotation) < 30){
// Angle from initial to new rotation is under 30 degrees
}
For the second part, you'll need some way of reducing the supplied rotation so it is within the allowable angle from the initial rotation. For that, Quaternion.Slerp()
is useful. This allows you to interpolate between two rotations, returning a Quaternion
that is a combination of the two supplied. For example, this gives back half of newRotation
:
Quaternion.Slerp(Quaternion.identity, newRotation, 0.5f);
Putting these two methods together, you can write a clamping method which ensures that the supplied rotation never exceeds a certain angle from the initial rotation. Here's an example usage:
// Maximum angle joystick can tilt at
public float tiltAngle;
// If this isn't your initial rotation, set it in Awake() or Start()
Quaternion initialRotation = Quaternion.identity;
void Update(){
Quaternion newRotation = MethodToGetSuppliedRotation();
Quaternion clampedRotation = ClampRotation(initialRotation, newRotation, tiltAngle);
transform.localRotation = clampedRotation;
}
// Clamps "b" such that it never exceeds "maxAngle" degrees from "a"
Quaternion ClampRotation(Quaternion a, Quaternion b, float maxAngle){
float newAngle = Quaternion.Angle(a, b);
if (newAngle <= maxAngle){
// Rotation within allowable constraint
return b;
}
else{
// This is the proportion of the new rotation that is within the constraint
float angleRatio = maxAngle / newAngle;
return Quaternion.Slerp(a, b, angleRatio);
}
}
Hope this helps! Let me know if you have any questions.