如何使用Mathf.Clamp在2个区域上旋转Z轴上的2D GameObject?
我想在Z轴上旋转一个2D游戏对象。该游戏对象只能在玩家在两个区域之间时面对。 Z轴应夹在-45至45至135至225之间。
(绿色是函数:lookattarget()
的函数)
现在,我正在使用此代码绕过问题,但是它并不令人满意:
public virtual void LookAtTarget()
{
float rotationZ = direction.transform.rotation.z;
direction.transform.right = target.position - transform.position;
if (rotationZ > -0.25F && rotationZ < 0.25F || rotationZ > 0.975F)
{
transform.right = target.position - transform.position;
}
Debug.Log(rotationZ);
}
我m使用这种类型的代码,因为当我与Eulerangles交谈时,我无法将值夹在-45和45之间,并且因为-45的统一度就像315度,所以我无法陷入负数。另外,我宣布从另一个游戏对象的旋转来告诉我玩家何时在特定范围内。
我希望我可以解释我的问题。泰
I want to rotate a 2D game object on the z axis. That game object should only face the Player when he is in between 2 areas. The Z-axis should be clamped between -45 to 45 and 135 to 225.
Example Image of the rotations
(The green are is where the function: LookAtTarget()
should be applied to)
Right now I'm using this code to bypass the problem, but it doesn't feel very satisfying:
public virtual void LookAtTarget()
{
float rotationZ = direction.transform.rotation.z;
direction.transform.right = target.position - transform.position;
if (rotationZ > -0.25F && rotationZ < 0.25F || rotationZ > 0.975F)
{
transform.right = target.position - transform.position;
}
Debug.Log(rotationZ);
}
I'm using this type of code because when I'm talking to eulerAngles I can't clamp the value between -45 and 45 and because -45 its like 315 degree for unity, so I can't go into the negative numbers. Also I'm declearing the rotation from another game object that should tell me when the Player is in the specific range.
I hope i could explain my problem. TY
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
transform.Rotation
是以Quaternion
表示的转换的旋转。要获取围绕Z轴的旋转,请使用Direction.transform.eulerangles.z
。始终使用eulerangles
,除非您了解quaternions
。我不明白您的代码在做什么,但这是夹紧旋转的想法。此代码未经测试。关键是Mathf.deltaangle(a,b),即使角度包裹着角度,它也从A到B返回最短角度([-180,180])。
Transform.rotation
is the rotation of the transform expressed as aQuaternion
. To get the rotation around the z-axis, usedirection.transform.eulerAngles.z
. Always useeulerAngles
unless you understandQuaternions
.I cannot understand what your code is doing, but here is an idea to clamp rotation. This code is untested. The key is Mathf.DeltaAngle(a, b) which returns the shortest angle (range of [-180, 180]) from a to b, even if the angles wrap around.