首页 文章

在Unity中围绕X轴和Y轴旋转对象

提问于
浏览
1

我正试图通过拖动屏幕在Android设备上旋转我的相机 . 水平拖动应将相机移动到 leftright 并垂直移动 updown . Z axis 应该被忽略,但是如果我在屏幕上进行对角线拖动,它会围绕 Z axis 旋转相机,所以有时我的相机会有一个颠倒的位置 .

这是我的 Update() 方法的代码:

if (touch.phase  == TouchPhase.Moved)
{
    float x = touch.deltaPosition.x * rotationSensitivity * Time.deltaTime;
    float y = touch.deltaPosition.y * rotationSensitivity * Time.deltaTime;

    _camera.transform.Rotate(new Vector3(1, 0, 0), y, Space.Self);
    _camera.transform.Rotate(new Vector3(0, -1, 0), x, Space.Self); 

}

1 回答

  • 1

    您正在使用错误的 transform.Rotate 重载

    您正在使用的第一个 Vector3 参数是 axis 旋转 .

    我相信你的意思是提供方向,而不是轴,如下:

    if (touch.phase  == TouchPhase.Moved)
    {
        Vector2 rotation = (Vector2)touch.deltaPosition * rotationSensitivity * Time.deltaTime;
    
        _camera.transform.Rotate(Vector3.right * rotation.x, Space.Self);
        _camera.transform.Rotate(-Vector3.up * rotation.y, Space.Self); 
    }
    

    由于此代码未经我测试,我还建议尝试这样做:

    if (touch.phase  == TouchPhase.Moved)
    {
        Vector2 rotation = (Vector2)touch.deltaPosition * rotationSensitivity * Time.deltaTime;
    
        _camera.transform.Rotate(transform.right * rotation.x, Space.World);
        _camera.transform.Rotate(-transform.up * rotation.y, Space.World); 
    }
    

    编辑:我把 xy 混淆了,修复了 .

相关问题