Reputation: 46
When I want to move Camera from origin position to destination position,it looks so stiff.So if it can set move speed accordding to offset,how to do ?
Upvotes: 2
Views: 25009
Reputation: 6052
There is a nice tutorial on this problem, it is normally described at the beginning of all tutorials on the unity website. Inside the Survival Shooter Tutorial there is a explanation how to make the movement of the camera to the destination position smooth while moving.
Here is the code for moving the camera. Create a script, add it to the camera and add the GameObject
you want to move to, into the scripts placeholder. It will automatically save the Transform component like setup in the script. (In my case its the player of the survival shooter tutorial ):
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);
}
}
Upvotes: 3
Reputation: 46
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);
}
}
Upvotes: 1
Reputation: 1496
Have you tried using Vector3.MoveTowards? You can specify the step size to use, which should be smooth enough.
http://docs.unity3d.com/Documentation/ScriptReference/Vector3.MoveTowards.html
Upvotes: 1
Reputation: 1035
You can use iTween plugins. And if you want your camera to move with your object ie to follow it smoothly. You can use smoothFollow script.
Upvotes: 2