【问题标题】:Move camera between min and max X, Y and Z coordinates in Unity在 Unity 中的最小和最大 X、Y 和 Z 坐标之间移动相机
【发布时间】:2018-08-03 17:34:57
【问题描述】:

我正在使用 Unity 制作 3D 游戏,并将使用 ZQS 来移动相机D(我使用 Azerty 键盘) 和鼠标滚轮进行缩放。 escape 键将切换相机的移动。

我会让我的相机保持在最小和最大区域内。为此,我使用Vector3 类型的两个变量minmax。这是 Main Camera 在 Unity 中的配置:

这是我的代码:

using UnityEngine;

public class CameraController : MonoBehaviour
{
    [Header("Speeds")]
    public float panSpeed = 30;
    public float scrollSpeed = 5;

    [Header("Movement")]
    public bool doMovement = true;

    [Header("Min and max values")]
    public Vector3 min;
    public Vector3 max;

    private void Update()
    {
        if (Input.GetKey(KeyCode.Escape))
        {
            doMovement = !doMovement;
        }

        if (doMovement)
        {
            if (Input.GetKey(KeyCode.Z))
            {
                Move(Vector3.forward);
            }
            else if (Input.GetKey(KeyCode.S))
            {
                Move(Vector3.back);
            }
            else if (Input.GetKey(KeyCode.Q))
            {
                Move(Vector3.left);
            }
            else if (Input.GetKey(KeyCode.D))
            {
                Move(Vector3.right);
            }

            float scroll = Input.GetAxis("Mouse ScrollWheel") * 1000;

            Vector3 pos = transform.position;
            pos.y -= scroll * scrollSpeed * Time.deltaTime;
            pos.y = Mathf.Clamp(pos.y, min.y, max.y);
            transform.position = pos;
        }
    }

    private void Move(Vector3 direction)
    {
        Vector3 pos = direction * panSpeed * Time.deltaTime;
        pos.x = Mathf.Clamp(pos.x, min.x, max.x);
        pos.z = Mathf.Clamp(pos.z, min.z, max.z);

        transform.Translate(pos, Space.World); // problem 1 
        transform.position = pos;              // problem 2
    }
}

问题是当我使用按键移动相机时。我尝试了两行不同的代码,但两者都不能正常工作。这是我的问题。上面我的代码的注释行。

  • 第一行忽略最小值和最大值。

  • 第二行设置相机在移动时始终打开(0, 10, 0.4970074)。在我按下 Q 之后是这样的:

我不会同时使用两条线。

你能找到问题吗?

【问题讨论】:

  • 您确定问题不在于您使用的是透视相机而不是正交相机吗?
  • @gkgkgkgk:我正在使用透视图。查看我的配置图片:i.stack.imgur.com/etgdy.png

标签: c# unity3d camera


【解决方案1】:
  • 第 1 行不起作用,因为transform.Translate 将沿向量移动对象,而不是向某个位置移动。您的代码正在以一定速度平移对象,并限制速度而不是位置。

  • 第 2 行不起作用,因为将移动向量分配给该位置只会将相机移动到您的向量值。

试试这个:

transform.Translate(direction * panSpeed * Time.deltaTime);  // move object
Vector3 pos = transform.position; // get position as Vector
pos.x = Mathf.Clamp(pos.x, min.x, max.x); // clamp position
pos.z = Mathf.Clamp(pos.z, min.z, max.z);
transform.position = pos; // reassign clamped Vector to position

【讨论】:

  • 不编译。在第一行得到这个错误。 Argument 2: cannot convert from 'UnityEngine.Vector3' to 'float'
  • @H.Pauwelyn 哎呀,我会解决的。 (对不起,这不是我的想法)
  • 只需要在第一行之前添加float y = transform.position.y;,在pox.x = ...pos.z = ...之间添加pos.y = y;。这必须是因为 X 轴上的旋转是 65 度。没有这个,它会缩放相机。
猜你喜欢
  • 2013-02-27
  • 2011-05-13
  • 1970-01-01
  • 2021-04-11
  • 2014-05-30
  • 1970-01-01
  • 1970-01-01
  • 2012-10-07
  • 2020-03-20
相关资源
最近更新 更多