首页 文章

变换:鼠标方向不正确

提问于
浏览
0

我有以下鼠标代码(C#with Unity)用鼠标(x,y和z)旋转相机 . 但是当我用鼠标旋转相机时,相机会以偏移量移动 .

void Update()
{
    Turn();
    Thrust();
}

void Turn()
{
    float yaw = turnSpeed * Time.deltaTime * Input.GetAxis("Mouse X");  //Horizontal
    float pitch = turnSpeed * Time.deltaTime * Input.GetAxis("Mouse Y");  //Pitch
    float roll = turnSpeed * Time.deltaTime * Input.GetAxis("Roll") //Roll
    transform.Rotate(-pitch, yaw, -roll) 

}

我希望相机随着鼠标的移动而移动(就像FPS一样) . 这段代码有什么问题?

EDIT

从副本中尝试了解决方案 . 当我在x轴上旋转摄像机超过/ - 180度时,我遇到了万向节锁定问题(左侧变为右侧和右侧变为左侧) .

public class Movement002 : MonoBehaviour {

public float xMoveThreshold = 1000.0f;
public float yMoveThreshold = 1000.0f;

public float yMaxLimit = 45.0f;
public float yMinLimit = -45.0f;


float yRotCounter = 0.0f;
float xRotCounter = 0.0f;

Transform player;

void Start()
{

    player = this.transform.parent.transform;
}

// Update is called once per frame
void Update()
{
    xRotCounter += Input.GetAxis("Mouse X") * xMoveThreshold * Time.deltaTime;
    yRotCounter += Input.GetAxis("Mouse Y") * yMoveThreshold * Time.deltaTime;
    //yRotCounter = Mathf.Clamp(yRotCounter, yMinLimit, yMaxLimit);
    //xRotCounter = xRotCounter % 360;//Optional
    player.localEulerAngles = new Vector3(-yRotCounter, xRotCounter, 0);
}

}

1 回答

  • 0

    我找到了你的答案,here这个页面包含一个名为mouselook的类,这是一个统一资产,你可以通过Unity Asset Demo Package免费获得 . 但如果你愿意,你可以在这里 grab 剧本 .

    更多关于你做什么......从编程的角度来看,你可以更容易地将一个脚本放在相机上,它使用 transform.lookAt()

    Vector3 point = new Vector3();
            Event   currentEvent = Event.current;
            Vector2 mousePos = new Vector2();
    
            // Get the mouse position from Event.
            // Note that the y position from Event is inverted.
            mousePos.x = currentEvent.mousePosition.x;
            mousePos.y = cam.pixelHeight - currentEvent.mousePosition.y;
    
            point = cam.ScreenToWorldPoint(new Vector3(mousePos.x, mousePos.y, cam.nearClipPlane));
    transform.LookAt(point);
    

    你可以把它放在你的相机上并给它一个旋转 . 重要的是要注意:

    mousePos.y = cam.pixelHeight - currentEvent.mousePosition.y;
    

    因为从屏幕点转换到您的世界中的某个点,并且鼠标y在屏幕位置反转,所以这会为您翻转它 . 祝好运 .

相关问题