Developedia
Developedia

Karakter követő kamera (Csak kód)

using UnityEngine;

public class FollowerCamera2D : MonoBehaviour
{ 
	[Header("References")]
	[SerializeField] Rigidbody2D targetRigidbody2D;

	[Header("Horizontal Movement")]
	[SerializeField] float maxXTargetSpeed = 10f;
	[SerializeField] float offsetXAtIdle = 2f; 
	[SerializeField] float offsetXAtMaxSpeed = 4.5f;
	[SerializeField] float smoothTimeX = 0.35f;

	[Header("Vertical Movement")]
	[SerializeField] float smoothTimeY = 0.1f;
	
	Vector2 _velocity = Vector2.zero;
	
	void Start()
	{
		Vector3 currentPoint = transform.position;
		Vector2 targetPoint = GetTargetPoint();
		transform.position = new Vector3(targetPoint.x, targetPoint.y, currentPoint.z);
	}
	
	void LateUpdate()
	{
		Vector3 currentPoint = transform.position;
		Vector2 targetPoint = GetTargetPoint();
		        
		float smoothedX = 
			Mathf.SmoothDamp(currentPoint.x, targetPoint.x, ref _velocity.x, smoothTimeX);
		float smoothedY = 
			Mathf.SmoothDamp(currentPoint.y, targetPoint.y, ref _velocity.y, smoothTimeY);
		        
		transform.position = new Vector3(smoothedX, smoothedY, currentPoint.z);
	}
	
	void OnDrawGizmos()
	{
		Gizmos.color = Color.red;
		Vector3 targetPoint = GetTargetPoint();
		Gizmos.DrawWireSphere(targetPoint, 0.1f);
		Vector3 currentPoint = transform.position;
		Gizmos.DrawLine(currentPoint, targetPoint);
	}
	    
	Vector2 GetTargetPoint()
	{
		float targetHorizontalSpeed = Mathf.Abs(targetRigidbody2D.velocity.x);
		float t = targetHorizontalSpeed / maxXTargetSpeed;
		float offset = Mathf.Lerp(offsetXAtIdle, offsetXAtMaxSpeed, t);
		Vector2 offsetVector = targetRigidbody2D.transform.right * offset;
		return targetRigidbody2D.position + offsetVector;
	}
}
Logo

Főoldal

Blog

Elmélet

3D Studio

Adatvédelmi nyilatkozat

GY.I.K.

Házirend

Szerző: Marosi Csaba / marosi.csaba@3d-studio.hu

DiscordGitHubLinkedIn