c - 旋转 90 度统一
问题描述
我正在尝试围绕我的鼠标旋转我的 2d 对象。这是我拥有的代码:
void Update()
{
Vector3 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector3 direction = mousePosition - transform.position;
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0, 0, angle);
// Debug.Log(angle);
}
我的对象是一个箭头,默认情况下是向下的,所以在我开始脚本之前我将它的z旋转设置为90,所以它面向右。如果我删除transform.rotation线,显示的角度将是正确的,当我的光标在上面写着 90,在左边写着 180 等等。所以我的问题是,为什么我需要在角度上加上 90 度才能使它真正起作用?为什么这个版本不起作用?谢谢!
解决方案
返回值是x 轴[=
Vector3.right
] 和从零开始到 (x,y) 终止的二维向量之间的角度。
如果默认情况下您的箭头指向右侧但您的箭头指向右侧,它将按预期工作
默认指向下方
您可以简单地在顶部添加偏移旋转,例如
transform.rotation = Quaternion.Euler(0, 0, angle + 90);
或者,如果您需要具有不同偏移量的多个对象,请使用可配置字段,例如
[SerializeField] private float angleOffset;
...
transform.rotation = Quaternion.Euler(0, 0, angle + angleOffset);
或者您可以在启动应用程序之前手动旋转它以正确面向右侧并存储默认的偏移旋转,例如
private Quaternion defaultRotation;
private void Awake ()
{
defaultRotation = transform.rotation;
}
然后做
transform.rotation = defaultRotation * Quaternion.Euler(0, 0, angle);
推荐阅读
- ansible - In ansible using the value of a previously assigned set_fact in a when conditional for jira task skips even though condition is met
- python - 归并排序算法的递归
- git-bash - 如何在 git bash 中打印文本文件的内容?
- xamarin.forms - 如何在 Xamarin.Forms.maps.map 上显示选择器
- android - 使用 button.performClick() 时不会显示飞溅片段
- python - TWS IB网关(版本972/974)客户端不断断开
- javascript - Xamarin.Forms/Asp.Net Core 自定义 WebView 集成
- python - 从 Python 中的二进制图像获取像素边界坐标(不是边缘)
- c - 在C中将整数转换为文字字符数组
- java - OWASP ESAPI 找不到我的 ESAPI.properties 文件,尽管它存在于目录中