c# - unity 添加单轴旋转
问题描述
美好的一天,将单轴添加到旋转时遇到问题。我有一个外部方法,可以在平面上设置 2d 旋转,绑定到玩家角色。但它不能使用 Y 轴,因此武器旋转仅限于 xz 平面。暴露的方法有一个旋转的 queterion 条目,我正在努力向它添加一个垂直部分。
protected virtual void RotateWeapon(Quaternion newRotation)
{
if (GameManager.Instance.Paused)
{
return;
}
RaycastHit hit;
Physics.Raycast(_reticlePosition, Vector3.down * 1000, out hit);
Debug.DrawLine(_reticlePosition, hit.point, Color.red);
//Hit.point.z is a vertical part i need to add to newRotation
// if the rotation speed is == 0, we have instant rotation
if (WeaponRotationSpeed == 0)
{
transform.rotation = newRotation;
}
// otherwise we lerp the rotation
else
{
transform.rotation = Quaternion.Lerp(transform.rotation, newRotation, WeaponRotationSpeed * Time.deltaTime);
}
解决方案
Quaternions
您可以通过将两者与*
运算符相乘来添加旋转,例如
newRotation *= additionalRotation;
然后为了生成,additionalRotation
您可以使用Quaternion.Euler
并传入一个Vector3
表示旋转拆分为每个轴的欧拉角分量的值。
我没有完全理解你的用例,但如果你想旋转,例如只围绕 Z 轴,你会做
newRotation *= Quaternion.Euler(Vector3.forward * angle);
或者,如果您更愿意采用给定Quaternion
但将其限制为仅在 Z 等某个轴上旋转,您可以使用
newRotation = Quaternion.Euler(Vector3.Scale(Vector3.forward, newRotation.euerAngles));
您可以将 替换为Vector3.forward
任何其他向量,指示应该使用哪些轴角度,例如new Vector3(1,0,1)
保持 X 和 Z 旋转但消除 Y 旋转(请参阅Vector3.Scale
)
推荐阅读
- django - 在 Django admin 的必填字段中添加星号
- amazon-web-services - 如何在s3中附加来自不同文件夹的多个csv文件
- kubernetes - 在一台虚拟机上使用混合容器的 Kubernetes?
- angular - 可能由于角度 5 中的解析而无法进行路线导航?
- javascript - 如何将带有“< >”字符的文本作为纯文本插入到 TinyMCE 中,而不将其视为 HTML 标记
- javascript - 如何将选定的属性设置为触发 Reactjs 中的 onChange(event) 方法的事件
- c# - 将 DateTime 转换为整数
- mysql - SQL忽略条件中的字符串
- excel - 如何使用excel函数(左/右/中)提取由相同符号环绕的字符串?
- php - PHP 和 MYSQL 连接的 Denied Permissions 问题