旋转相机时对象旋转不正确

时间:2017-04-18 18:44:04

标签: c# unity3d camera rotation raycasting

我有一个摄像头,它将userInterface(画布)对象显示在我的摄像头前面。 如果相机光线投射未击中我的userInterface对象碰撞器,我只更新我的用户界面位置。像这样的东西

public class UIPlacerAtCamFront : MonoBehaviour {

    public GameObject userInterface;
    public float placementDistance;
    Vector3 uiPlacementPosition;
    RaycastHit  objectHit; 

    void Update () {

        Vector3 fwd = this.transform.TransformDirection(Vector3.forward);
        //Debug.DrawRay(this.transform.position, fwd * 50, Color.green);

        if (Physics.Raycast(this.transform.position, fwd, out objectHit, 50))
        {
            //raycast hitting the userInterface collider, so do nothing, userinterface is infornt of the camrea already
        }
        else
        {
            //raycast is not hitting userInterfae collider, so update UserInterface position accoding to the camera
            uiPlacementPosition = this.transform.position + this.transform.forward * placementDistance;
            userInterface.transform.position = uiPlacementPosition;
        }

        //Continuously update userInterface rotation according to camera
        userInterface.transform.rotation = this.transform.rotation; 
    }
}

上面的脚本附有我的相机,它正确显示对象但是当我开始旋转我的相机时,我的UI对象旋转看起来很奇怪,如下图所示 This is inital correct rotation

当我旋转时,会出现此问题 enter image description here

我知道问题在于轮换,所以我厌倦了改变我的旋转代码

    userInterface.transform.rotation = this.transform.rotation; 

到这个

userInterface.transform.localEulerAngles = new Vector3 (this.transform.localEulerAngles.x,
            0,
            this.transform.localEulerAngles.z);

但它为我带来了另一个奇怪的轮换,如下所示 enter image description here

我希望我的userinteface对象面对我的相机,即使我的相机正在观察我的用户界面对象的开头或结尾。如何根据相机旋转正确旋转我的UI?

1 个答案:

答案 0 :(得分:0)

如果我理解正确的话。你想要一个类似于滑动谷歌地图的行为。只有相机必须旋转,图片必须调整其位置和旋转行为。

以下代码应该这样做:

void Update() {
    userInterface.transform.rotation = this.transform.rotation;

    // Project camera to canvas plane
    Vector3 projection = Vector3.ProjectOnPlane(this.transform.position - userInterface.transform.position, userInterface.transform.forward)
        + userInterface.transform.position;

    // Get distance from camera to projected position (basically, distance from point to plane)
    float curDistance = (this.transform.position - projection).magnitude;

    // Correct that distance with desired distance
    userInterface.transform.position += this.transform.forward * (placementDistance - curDistance);
}