Camera Movement – Example 2
•
Example 2: Following a target position (smooth camera movement)
public class CameraController : MonoBehaviour{
private SpriteRenderer player;
private Vector3 targetPosition;
public float targetOffset = 4;
public float adjustOffsetSpeed = 2.5f;
private void Start(){
player = GameObject.FindWithTag("Player").GetComponent<SpriteRenderer>();
}
private void FixedUpdate(){
if (player.flipX){
targetPosition = new Vector3(player.transform.position.x –
targetOffset, transform.position.y, transform.position.z);
}
else{
targetPosition = new Vector3(player.transform.position.x +
targetOffset, transform.position.y, transform.position.z);
}
transform.position = Vector3.Lerp(transform.position, targetPosition,
adjustOffsetSpeed * Time.deltaTime);
}
}