我想在任何方向上自由旋转我的游戏对象360度,以便在父游戏对象周围的平滑轨道上发送任何偏移子对象 .
不幸的是,尽管经过了数天的研究,我仍然在努力获得正常行为的基本轮换要求 . 在少量旋转之后,其中一个轴开始以不可预测的方向旋转 .
如果我只是在一个轴上旋转,它就能很好地工作 . 只有当我希望在x和y轴上旋转对象时,才会出现此问题 .
这个gif显示了我的工作样本 . 我不断地将鼠标移向屏幕的左下方向,我希望黄色立方体围绕球体旋转,最终在它开始的地方 . 但是,经过超过45度后,它开始疯狂旋转:
我试图使用transform.Rotate,Quaternion.Euler和Quaternion.AngleAxis来实现这个功能,您可以在下面看到我的代码示例 . 不幸的是问题仍然存在,我对所有这些问题都得到了同样不正确的行为 .
使用transform.Rotate:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Orbit : MonoBehaviour
{
private Vector3 TargetMoveDir = Vector3.zero;
private void Start()
{
Cursor.lockState = CursorLockMode.Locked;
}
private void LateUpdate()
{
float targetMoveX = Input.GetAxis("Mouse X");
float targetMoveY = Input.GetAxis("Mouse Y");
if (targetMoveX != 0 || targetMoveY != 0)
{
float rotateSpeed = Time.deltaTime * 60f;
transform.Rotate(0f, -targetMoveX * rotateSpeed, 0f, Space.World);
transform.Rotate(targetMoveY * rotateSpeed, 0f, 0f, Space.Self);
}
}
}
使用Quaternion.Euler:
float rotateSpeed = Time.deltaTime * 60f;
TargetMoveDir.y -= targetMoveX * rotateSpeed;
TargetMoveDir.x += targetMoveY * rotateSpeed;
Quaternion rotation = Quaternion.Euler(TargetMoveDir);
transform.localRotation = rotation;
使用Quaternion.AngleAxis:
float rotateSpeed = Time.deltaTime * 60f;
TargetMoveDir.y -= targetMoveX * rotateSpeed;
TargetMoveDir.x += targetMoveY * rotateSpeed;
Quaternion rotF = Quaternion.AngleAxis(0, Vector3.forward);
Quaternion rotU = Quaternion.AngleAxis(TargetMoveDir.y, Vector3.up);
Quaternion rotR = Quaternion.AngleAxis(TargetMoveDir.x, Vector3.right);
transform.rotation = Quaternion.identity * rotF * rotU * rotR;
请有人帮帮我吗?
1 回答
我不确定你的预期行为是什么,但据我所知,我建议:
如果我误解了你想要实现的目标,请尝试告诉我 .