Hey Guys,
i need help. I wanna create a RTS topdown camera. I’ve got much already finished, but i cant get the camera limit .
i know it has something to do with mathf ,clamp etc.
but i dont know how to add it.
in general
i wanna limit the camera, so that you cant move endlessly away from the map.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class CameraController : MonoBehaviour
{
// Start is called before the first frame update
public float moveSpeed;
public float zoomSpeed;
public float leftLimit;
public float rightLimit;
public float bottomLimit;
public float topLimit;
public float minZoomDist;
public float maxZoomDist;
public float dragSpeed = 0.1f;
private Vector3 dragOrigin;
private Camera cam;
// Update is called once per frame
private void Awake()
{
cam = Camera.main;
}
void Update()
{
Move();
Zoom();
Limit();
if (Input.GetMouseButtonDown(1))
{
dragOrigin = Input.mousePosition;
return;
}
if (!Input.GetMouseButton(1)) return;
Vector3 pos = Camera.main.ScreenToViewportPoint(Input.mousePosition - dragOrigin);
Vector3 move = new Vector3(pos.x * dragSpeed, 0, pos.y * dragSpeed);
transform.Translate(move, Space.World);
}
void Move()
{
float xInput = Input.GetAxis("Horizontal");
float zInput = Input.GetAxis("Vertical");
Vector3 dir = transform.forward * zInput + transform.right * xInput;
transform.position += dir * moveSpeed * Time.deltaTime;
}
void Limit()
{
transform.position = new Vector3
(
Mathf.Clamp(transform.position.x, leftLimit, rightLimit),
Mathf.Clamp(transform.position.y, bottomLimit, topLimit),
transform.position.z
);
}
void Zoom()
{
float scrollInput = Input.GetAxis("Mouse ScrollWheel");
float dist = Vector3.Distance(transform.position, cam.transform.position);
if (dist < minZoomDist && scrollInput > 0.0f)
return;
else if (dist > maxZoomDist && scrollInput < 0.0f)
return;
cam.transform.position += cam.transform.forward * scrollInput * zoomSpeed;
}
}
For left and right it is working but not for up and down…