如何在unity3D中顺利移动相机?

时间:2014-01-03 06:27:49

标签: unity3d transform gameobject lerp

当我想将相机从原点位置移动到目标位置时,它看起来很僵硬。如果它可以根据偏移设置移动速度,该怎么办?

4 个答案:

答案 0 :(得分:2)

您可以使用iTween个插件。如果你想让你的相机与你的物体一起移动,即顺利地跟随它。您可以使用smoothFollow脚本。

答案 1 :(得分:1)

您是否尝试过使用Vector3.MoveTowards?您可以指定要使用的步长,这应该足够平滑。

http://docs.unity3d.com/Documentation/ScriptReference/Vector3.MoveTowards.html

答案 2 :(得分:1)

public Vector3 target;        //The player
public float smoothTime= 0.3f;  //Smooth Time
private Vector2 velocity;       //Velocity
Vector3 firstPosition;
Vector3 secondPosition;
Vector3 delta;
Vector3 ca;
tk2dCamera UICa;
bool click=false;
void Start(){
    ca=transform.position;
    UICa=GameObject.FindGameObjectWithTag("UI").GetComponent<tk2dCamera>();
}
void  FixedUpdate ()
{
    if(Input.GetMouseButtonDown(0)){


        firstPosition=UICa.camera.ScreenToWorldPoint(Input.mousePosition);
        ca=transform.position;

    }
    if(Input.GetMouseButton(0)){


        secondPosition=UICa.camera.ScreenToWorldPoint(Input.mousePosition);
        delta=secondPosition-firstPosition;
        target=ca+delta;

    }
    //Set the position
    if(delta!=Vector3.zero){
        transform.position = new Vector3(Mathf.SmoothDamp(transform.position.x, target.x, ref velocity.x, smoothTime),Mathf.SmoothDamp( transform.position.y, target.y, ref velocity.y, smoothTime),transform.position.z);
    }

}

答案 3 :(得分:1)

关于这个问题有一个很好的教程,它通常在统一网站上的of all tutorials开头描述。在Survival Shooter Tutorial内部有一个解释,说明如何在移动时使摄像机移动到目标位置。“

以下是移动相机的代码。创建一个脚本,将其添加到摄像头并将要移动的GameObject添加到脚本占位符中。它将自动保存Transform组件,如脚本中的setup。 (就我而言,它是生存射手教程的玩家):

public class CameraFollow : MonoBehaviour
{
    // The position that that camera will be following.
    public Transform target; 
    // The speed with which the camera will be following.           
    public float smoothing = 5f;        

    // The initial offset from the target.
    Vector3 offset;                     

    void Start ()
    {
        // Calculate the initial offset.
        offset = transform.position - target.position;
    }

    void FixedUpdate ()
    {
        // Create a postion the camera is aiming for based on 
        // the offset from the target.
        Vector3 targetCamPos = target.position + offset;

        // Smoothly interpolate between the camera's current 
        // position and it's target position.
        transform.position = Vector3.Lerp (transform.position, 
                                           targetCamPos,   
                                           smoothing * Time.deltaTime);
    }
}