c# - 线性旋转 2D 对象
问题描述
我的 2D 对象正在查找 ( transform.up = (0,1)
)。
当我单击屏幕中的某个位置时,我希望对象查看我单击的位置。我还希望它线性旋转:它应该d
每秒旋转度数,这意味着旋转两倍的角度需要两倍的时间。
这是我的代码:
void Update() {
if (Input.GetMouseButtonDown(0)) {
Vector2 wPos = cameraRef.ScreenToWorldPoint(Input.mousePosition);
StartCoroutine(LookAt(mouseScreenPosition));
}
}
public IEnumerator LookAt(Vector2 position) {
Vector2 direction = (position - (Vector2) transform.position).normalized;
float angle = Vector2.SignedAngle(direction, transform.up);
float startAngle = transform.eulerAngles.z;
for(float t = 0; t <= 1; t += Time.deltaTime * (180 / Mathf.Max(1, Mathf.Abs(angle)))) {
transform.eulerAngles = new Vector3(0, 0, Mathf.Lerp(startAngle, startAngle - angle, t));
yield return null;
}
}
我乘以的因子Time.deltaTime
是180 / Mathf.Max(1, Mathf.Abs(angle))
,它表示角度越大,旋转所需的时间越长,但我不知道我是否做得对(它有效)或者这是否是更好的方法.
解决方案
定义一些rotationSpeed
字段:
public float rotationSpeed = 90f;
用于Quaternion.LookRotation
获取Quaternion
您想要旋转的方向。您希望本地前向指向全局前向,本地向上指向目标位置,因此使用Quaternion.LookRotation(Vector3.forward,targetDirection)
:
public IEnumerator LookAt(Vector2 position) {
// casting to Vector2 and normalizing is redundant
Vector3 targetDirection = position - transform.position;
Quaternion targetRotation = Quaternion.LookRotation(Vector3.forward, targetDirection);
然后使用Quaternion.RotateTowards
要在该帧中旋转的最大度数,直到完成向目标旋转的旋转:
while (Quaternion.Angle(targetRotation, transform.rotation) > 0.01)
{
transform.rotation = Quaternion.RotateTowards(transform.rotation, targetRotation,
time.deltaTime * rotationSpeed);
}
共:
public float rotationSpeed = 90f;
public IEnumerator LookAt(Vector2 position) {
// casting to Vector2 and normalizing is redundant
Vector3 targetDirection = position - transform.position;
Quaternion targetRotation = Quaternion.LookRotation(Vector3.forward, targetDirection);
while (Quaternion.Angle(targetRotation, transform.rotation) > 0.01)
{
transform.rotation = Quaternion.RotateTowards(transform.rotation, targetRotation,
time.deltaTime * rotationSpeed);
}
}
推荐阅读
- oracle - ORA-01653: 无法在表空间 SYSAUX 中将表 SYS.SQLOBJ$PLAN 扩展 128
- jquery - 使用 Flot 绘图:渲染的空白区域
- python-3.x - 如何在 AWS MWAA Airflow DAG 上获得 pyodbc 连接?
- spring-cloud-function - 带有 Apache Kafka 触发器的 AWS Lambda 返回“问题:Lambda 内部错误。请联系 Lambda 客户支持。”
- button - 谷歌表格提交按钮,用于根据列数据将数据行传输到适当的谷歌表格
- arduino - NodeMCU esp8266 不断断开我的笔记本电脑与路由器的连接
- swift - SwiftUI 按钮大小/形状/颜色不变
- python - django过滤器选择,模板上的顺序选择,按过滤器中写入的顺序
- javascript - 向 Azure Blob 存储发出 GET 请求时授权失败 [REST API][Azure Blob 存储]
- java - 在检查 available() 后调用 read() 时,stdin 没有在 Windows 上回显(可中断的 readline 实现)