首页 文章

相对于旋转重置位置

提问于
浏览
1

目前我有以下两个问题:

  • 第一个问题是,当我重置相机位置时,我还必须重置相机旋转 . 这是因为我的相机偏移设置在z和y轴上略微偏离我的播放器的位置,显然这些值应该根据我的相机旋转而改变,虽然我不确定如何弄清楚这些值应该是什么 .

  • 我的第二个问题是我的旋转使用光线投影来找到屏幕的中间并确定其旋转原点,尽管它似乎略微偏离屏幕中间,因为它旋转时旋转原点也会移动,如果它确实在屏幕中间不应该完全静止吗?还有一种更好,更便宜的方式来实现我想要的旋转吗?

相关的代码:

void RotateCamera()
{
    //Find midle of screen
    Ray ray = Camera.main.ScreenPointToRay(new Vector3(Screen.width / 2, Screen.height / 2, 0));
    RaycastHit hitInfo;

    //Checks if ray hit something
    if (Physics.Raycast(ray, out hitInfo))
    {
        //Rotate left and right
        if (Input.GetKey(KeyCode.RightArrow))
        {
            transform.RotateAround(hitInfo.point, -Vector3.up, rotationSpeed * Time.deltaTime);
        }
        if (Input.GetKey(KeyCode.LeftArrow))
        {
            transform.RotateAround(hitInfo.point, Vector3.up, rotationSpeed * Time.deltaTime);
        }
    }

    //Draws Raycast
    Debug.DrawRay(ray.origin, ray.direction * 100, Color.yellow);
}

void ResetCameraPosition()
{
    //Reset and lock camera position
    transform.rotation = Quaternion.identity;
    transform.position = player.transform.position + cameraOffset;

}

Image displaying what I mean

1 回答

  • 0

    使用Camera.ScreenToWorldPoint在屏幕中间创建一个'target'以绕其旋转 . 删除所有光线投射的东西,因为你不需要它并用以下内容替换相关的位:

    float rotationSpeed = 45; // or whatever speed
    float distance = 5f; // or whatever radius for the orbit
    Vector3 target = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width / 2, Screen.height / 2, distance));
    
    if (Input.GetKey(KeyCode.RightArrow))
    {
        transform.RotateAround(target , -Vector3.up, rotationSpeed * Time.deltaTime);
    }
    if (Input.GetKey(KeyCode.LeftArrow))
    {
        transform.RotateAround(target , Vector3.up, rotationSpeed * Time.deltaTime);
    }
    

相关问题