我创建了新的 Unity 项目,在中心添加了一个立方体,现在想让玩家能够通过滑动和/或鼠标拖动围绕这个立方体旋转相机。

请说出实现这个的简单步骤或关键字以找到答案或在哪里阅读它?

最佳答案

public Transform Target;

public float distance = 2.0f;
public float xSpeed = 20.0f;
public float ySpeed = 20.0f;
public float yMinLimit = -90f;
public float yMaxLimit = 90f;
public float distanceMin = 10f;
public float distanceMax = 10f;
public float smoothTime = 2f;
float rotationYAxis = 0.0f;
float rotationXAxis = 0.0f;
float velocityX = 0.0f;
float velocityY = 0.0f;

void Update()
{
    if (Input.GetMouseButton(0))
    {
        velocityX += xSpeed * Input.GetAxis("Mouse X") * distance * 0.02f;
        velocityY += ySpeed * Input.GetAxis("Mouse Y") * 0.02f;
    }
    rotationYAxis += velocityX;
    rotationXAxis -= velocityY;
    rotationXAxis = ClampAngle(rotationXAxis, yMinLimit, yMaxLimit);

    Quaternion rotation = Quaternion.Euler(rotationXAxis, rotationYAxis, 0);

    Vector3 negDistance = new Vector3(0.0f, 0.0f, -distance);
    Vector3 position = rotation * negDistance + Target.position;

    transform.rotation = rotation;
    transform.position = position;
    velocityX = Mathf.Lerp(velocityX, 0, Time.deltaTime * smoothTime);
    velocityY = Mathf.Lerp(velocityY, 0, Time.deltaTime * smoothTime);
}

public static float ClampAngle(float angle, float min, float max)
{
    if (angle < -360F)
        angle += 360F;
    if (angle > 360F)
        angle -= 360F;
    return Mathf.Clamp(angle, min, max);
}

取自 https://answers.unity.com/questions/1257281/how-to-rotate-camera-orbit-around-a-game-object-on.html

如果您只想围绕特定轴旋转,例如围绕 Y,您基本上可以这样做
this.transform.RotateAround(Target.transform.position, Vector3.up, Input.GetAxis("Mouse X")*20.0f);

关于unity3d - 如何让玩家能够在 Unity 中围绕立方体旋转相机?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50887848/

10-13 05:14