create a script to control fighting game camera that follows 2 players and stays within a set box in unity in csharp

You can implement this behavior by creating a script that uses the camera's Transform component to follow two players and restrict its location within a defined box. Here is some sample code that you can use:

main.cs
using UnityEngine;

public class CameraController : MonoBehaviour
{
    public Transform player1;
    public Transform player2;
    public Vector2 offset;
    public Vector2 minPosition;
    public Vector2 maxPosition;

    private Vector3 targetPosition;

    private void Update()
    {
        // Calculate the midpoint between the two players
        float midX = (player1.position.x + player2.position.x) / 2f;
        float midY = (player1.position.y + player2.position.y) / 2f;

        // Move the camera to the midpoint with the desired offset
        targetPosition = new Vector3(midX + offset.x, midY + offset.y, transform.position.z);
        transform.position = Vector3.Lerp(transform.position, targetPosition, Time.deltaTime * 5f);

        // Clamp the camera position within the defined box
        float clampedX = Mathf.Clamp(transform.position.x, minPosition.x, maxPosition.x);
        float clampedY = Mathf.Clamp(transform.position.y, minPosition.y, maxPosition.y);
        transform.position = new Vector3(clampedX, clampedY, transform.position.z);
    }
}
1080 chars
29 lines

Here, the player1 and player2 variables are set to the Transforms of the two players that you want the camera to follow. The offset variable specifies the desired offset from the midpoint of the two players.

The minPosition and maxPosition variables represent the corners of the box in which the camera is allowed to move. You can adjust these variables to control the size and position of the camera's movement area.

In the Update method, we calculate the midpoint between the two players and use it to move the camera's position with the desired offset. Then, we clamp the camera's position within the defined box using Mathf.Clamp.

Attach this script to the camera in your game, and assign the appropriate Transforms and variables in the Inspector. The camera will now follow the two players and stay within the defined box.

gistlibby LogSnag