Dynamic Camera Control for Fighting Game

 avatar
unknown
csharp
a month ago
2.9 kB
9
Indexable
using UnityEngine;

public class FightingGameCamera : MonoBehaviour
{
    public Transform player1; // Assign Player 1's transform in the Inspector
    public Transform player2; // Assign Player 2's transform in the Inspector

    public float minX = -10f; // Minimum X boundary for the camera
    public float maxX = 10f;  // Maximum X boundary for the camera
    public float minY = 0f;   // Minimum Y boundary 
    public float maxY = 10f;  // Maximum Y boundary 
    public float zoomFactor = 1.5f; // Factor by which to zoom out based on distance
    public float zoomSpeed = 10f;   // Speed of zooming in and out
    public float followSpeed = 5f;  // Speed at which the camera follows the players

    public float minDistance = 2f;  // Minimum distance before zooming stops
    public float minZoom = 5f;      // Minimum zoom level (orthographic size)
    public float maxZoom = 10f;     // Maximum zoom level (orthographic size)

    private Camera cam;

    void Start()
    {
        cam = Camera.main; // Get the camera component
    }

    void LateUpdate()
    {
        if (player1 == null || player2 == null)
            return;

        // Calculate the midpoint between the players
        Vector3 middlePoint = (player1.position + player2.position) / 2f;

        // Draw X shape at the midpoint in the Scene view
        float crossSize = 0.15f; // Size of the cross for visibility
        Vector3 offset = new Vector3(crossSize, crossSize, 0);

        // Draw lines at a 45-degree angle to create an X
        Debug.DrawLine(middlePoint - offset, middlePoint + offset, Color.red);
        Debug.DrawLine(middlePoint + new Vector3(-crossSize, crossSize, 0), middlePoint + new Vector3(crossSize, -crossSize, 0), Color.red);

        // Calculate the distance between the players
        float distance = Vector3.Distance(player1.position, player2.position);

        // Set the camera position to the midpoint
        Vector3 newPosition = new Vector3(middlePoint.x, middlePoint.y, cam.transform.position.z);
        cam.transform.position = Vector3.Lerp(cam.transform.position, newPosition, followSpeed * Time.deltaTime);

        // Adjust the camera orthographic size based on the distance if it's greater than the minimum distance
        if (distance > minDistance)
        {
            float newOrthographicSize = Mathf.Clamp(distance / zoomFactor, minZoom, maxZoom);
            cam.orthographicSize = Mathf.Lerp(cam.orthographicSize, newOrthographicSize, zoomSpeed * Time.deltaTime);
        }

        // Clamp the camera position to the boundaries
        cam.transform.position = new Vector3(
            Mathf.Clamp(cam.transform.position.x, minX, maxX),
            Mathf.Clamp(cam.transform.position.y, minY, maxY),
            cam.transform.position.z
        );
    }
}
Leave a Comment