【问题标题】:Why is my camera orbit flying off in the negative z?为什么我的相机轨道在负 z 方向飞行?
【发布时间】:2015-11-12 22:41:38
【问题描述】:

我从一个已有一年历史的统一线程中提取了大部分代码。每当我运行它时,我的相机都会很快在负 z 方向上运行。我整天都在研究这些变量,但没有什么能让我觉得它很适合我。

z 每帧变化 5 个单位,这正是我为相机距离设置的值。这似乎是理解问题的关键。我的部分问题是我几乎不能使用变换和欧拉角来掌握移动的物体。感谢您的宝贵时间。

public GameObject cameraTarget = null;

public float cameraSpeedX = 120.0f; //x sensitivity
public float cameraSpeedY = 120.0f; //y sensitivity
public float cameraVelocityX = 0.0f;
public float cameraVelocityY = 0.0f;
public float cameraRotationX = 0.0f;
public float cameraRotationY = 0.0f;

public float cameraLimitMinY = -20f;
public float cameraLimitMaxY = 80f;

public float cameraDistance = 5.0f;
public float cameraDdistanceMin = 0.5f;
public float cameraDistanceMax = 15.0f;

// Use this for initialization
void Start () {
    gameObject.AddComponent<MeshFilter>();
    gameObject.AddComponent<MeshRenderer>();
    Vector3 angles = transform.eulerAngles;
    cameraRotationX = angles.x;
    cameraRotationY = angles.y;

    // Make the rigid body not change rotation
    if(GetComponent<Rigidbody>()){GetComponent<Rigidbody>().freezeRotation = true;}
    cameraTarget = gameObject;

}

void LateUpdate(){
    if (cameraTarget){
        if (Input.GetMouseButton(1)){
            cameraVelocityX += cameraSpeedX * Input.GetAxis("Mouse X") * 0.02f;
            cameraVelocityY += cameraSpeedY * Input.GetAxis("Mouse Y") * 0.02f;
        }

        cameraRotationY += cameraVelocityX;
        cameraRotationX -= cameraVelocityY;

        cameraRotationX = ClampAngle(cameraRotationX, cameraLimitMinY, cameraLimitMaxY);

        //Quaternion fromRotation = Quaternion.Euler(transform.rotation.eulerAngles.x, transform.rotation.eulerAngles.y, 0);
        Quaternion toRotation = Quaternion.Euler(cameraRotationX, cameraRotationY, 0);
        Quaternion rotation = toRotation;

        Vector3 negDistance = new Vector3(0.0f, 0.0f, -cameraDistance);
        Vector3 position = rotation * negDistance + cameraTarget.transform.position;

        transform.rotation = rotation;
        transform.position = position;

        cameraVelocityX = Mathf.Lerp(cameraVelocityX, 0, Time.deltaTime * 2.0f);
        cameraVelocityY = Mathf.Lerp(cameraVelocityY, 0, Time.deltaTime * 2.0f);

        print ("POSITION:"+transform.position);
    }
}

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);
}

【问题讨论】:

  • 您确定您没有将 cameraTarget 设置为相机本身?
  • 其实,现在想想……我可能有。
  • 哈哈。是的。这可以解释这种行为

标签: c# unity3d orbital-mechanics


【解决方案1】:

出于某种原因,我认为将相机脚本和游戏对象生成放在同一个对象中是个好主意。相机变换被应用于自身,这导致相机无休止地试图落后于自己。感谢 mprivat 的洞察力。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-02
    相关资源
    最近更新 更多