54 lines
1.4 KiB
C#
54 lines
1.4 KiB
C#
using UnityEngine;
|
|
|
|
public class CameraFollow2D : MonoBehaviour
|
|
{
|
|
public float damping = 1.5f;
|
|
public Vector2 offset = new(2f, 1f);
|
|
public bool faceLeft;
|
|
private Transform player;
|
|
private float lastX;
|
|
|
|
void Start()
|
|
{
|
|
offset = new Vector2(Mathf.Abs(offset.x), offset.y);
|
|
FindPlayer(faceLeft);
|
|
}
|
|
|
|
public void FindPlayer(bool playerFaceLeft)
|
|
{
|
|
player = GameObject.FindGameObjectWithTag("Player").transform;
|
|
lastX = player.position.x;
|
|
|
|
Vector3 startPosition = player.position;
|
|
if (playerFaceLeft)
|
|
startPosition.x -= offset.x;
|
|
else
|
|
startPosition.x += offset.x;
|
|
|
|
startPosition.y += offset.y;
|
|
startPosition.z = transform.position.z;
|
|
|
|
transform.position = startPosition;
|
|
}
|
|
|
|
void FixedUpdate()
|
|
{
|
|
if (!player) return;
|
|
|
|
float currentX = player.position.x;
|
|
if (currentX > lastX + 0.01f) faceLeft = false;
|
|
else if (currentX < lastX - 0.01f) faceLeft = true;
|
|
lastX = currentX;
|
|
|
|
Vector3 target = player.position;
|
|
if (faceLeft)
|
|
target.x -= offset.x;
|
|
else
|
|
target.x += offset.x;
|
|
|
|
target.y += offset.y;
|
|
target.z = transform.position.z;
|
|
|
|
transform.position = Vector3.Lerp(transform.position, target, damping * Time.deltaTime);
|
|
}
|
|
} |