Hello everyone,
I’m currently working on a project in Unity where I want to implement dynamic view changes using Cinemachine. The idea is to have multiple cameras with specific zone detections (using colliders, for example) that trigger the transition from one camera to another when the player enters or exits these zones.
Currently, I’m using colliders to detect the player’s entry into a specific zone, and I activate the camera associated with that zone. However, I’m wondering if there is a more efficient approach or best practices for managing these camera transitions.
Here’s an excerpt from my current code to give you an idea:
public class CameraSwitcher : MonoBehaviour
{
public CinemachineVirtualCamera cinemaActive;
void OnTriggerEnter2D(Collider2D collision)
{
if (collision.CompareTag("Player"))
{
cinemaActive.enabled = true;
CinemachineVirtualCamera[] allCameras = FindObjectsOfType<CinemachineVirtualCamera>();
foreach (CinemachineVirtualCamera camera in allCameras)
{
if (camera != cinemaActive)
{
camera.enabled = false;
}
}
}
}
}
I also set up a dynamic change of the camera offset depending on the positive or negative velocity of the character (To find out if the character goes left or right) :
Code (CSharp):
- ```csharp
using UnityEngine;
using Cinemachine;
public class CameraReturn : MonoBehaviour
{
public CinemachineVirtualCamera cinemaReturnOffset;
public Rigidbody2D player;
public float smoothingFactor = 1f; // Facteur de lissage
private Vector3 initialOffset;
private Vector3 targetOffset;
void Start()
{
initialOffset = cinemaReturnOffset.GetCinemachineComponent<CinemachineFramingTransposer>().m_TrackedObjectOffset;
targetOffset = initialOffset;
}
void Update()
{
CheckVelocity();
UpdateOffset();
Debug.Log(player.velocity.x);
}
void OnTriggerEnter2D(Collider2D collision)
{
if (collision.CompareTag("Player"))
{
// Lorsque le joueur entre dans la zone, vérifiez la vélocité
CheckVelocity();
}
}
void CheckVelocity()
{
if (player.velocity.x < -0.1f)
{
targetOffset.x = -Mathf.Abs(initialOffset.x);
}
else if (player.velocity.x > 0.1f)
{
targetOffset.x = Mathf.Abs(initialOffset.x);
}
}
void UpdateOffset()
{
CinemachineFramingTransposer framingTransposer = cinemaReturnOffset.GetCinemachineComponent<CinemachineFramingTransposer>();
framingTransposer.m_TrackedObjectOffset.x = Mathf.Lerp(framingTransposer.m_TrackedObjectOffset.x, targetOffset.x, smoothingFactor * Time.deltaTime);
}
}
Do you have any suggestions on how to improve this approach or recommendations on specific Cinemachine features that I could leverage to make these camera transitions smoother and more dynamic?
Thank you in advance for your help!
