- Home /
How to Limit the Camera Movement ?
Hi guys,
i asked this question already but i think i wasnt specific enough. So .. i wanna create an RTS like game and i have already implemented the Camera moving but i coudlt add a limit to the camera movement so it stops on the Map edges. i would be very grateful if someone could help me with this. Here is my last try that didnt work
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class CameraMovementScript : MonoBehaviour { float speed = 10.0f; float zoomspeed = 10.0f; float rotateSpeed = 30.0f;
float maxHeight = 150f;
float minHeight = 88f;
Vector2 p1;
Vector2 p2;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKey(KeyCode.LeftShift))
{
speed = 10.0f;
zoomspeed = 10.0f;
}
else
{
speed = 5.0f;
zoomspeed = 5.0f;
}
float hsp = transform.position.y * speed * Time.deltaTime * Input.GetAxis("Horizontal");
float vsp = transform.position.y * speed * Time.deltaTime * Input.GetAxis("Vertical");
float scrollSp = Mathf.Log(transform.position.y) * -zoomspeed * Input.GetAxis("Mouse ScrollWheel");
if ((transform.position.y >= maxHeight) && (scrollSp > 0))
{
scrollSp = 0;
}
else if ((transform.position.y <= minHeight) && (scrollSp <0))
{
scrollSp = 0;
}
if((transform.position.y + scrollSp) > maxHeight)
{
scrollSp = maxHeight - transform.position.y;
}
else if((transform.position.y + scrollSp) < minHeight)
{
scrollSp = minHeight - transform.position.y;
}
Vector3 verticalMove = new Vector3(0, scrollSp, 0);
Vector3 lateralMove = hsp * transform.right;
Vector3 forwardMove = transform.forward;
forwardMove.y = 0;
forwardMove.Normalize();
forwardMove *= vsp;
Vector3 move = verticalMove + lateralMove + forwardMove;
move.x = Mathf.Clamp(move.x, 800f, 1700f); <------- does not work
move.z = Mathf.Clamp(move.z, 300f, 1050f);
transform.position += move;
getCameraRotation();
}
void getCameraRotation()
{
if(Input.GetMouseButtonDown(2))//check if the middle mouse button is pressed
{
p1 = Input.mousePosition;
}
if(Input.GetMouseButton(2))//check if the middle mouse button is being hold
{
p2 = Input.mousePosition;
float dx = (p2 - p1).x * rotateSpeed * Time.deltaTime;
float dy = (p2 - p1).y * rotateSpeed * Time.deltaTime;
transform.rotation *= Quaternion.Euler(new Vector3(0, dx, 0)); //Y rotation
p1 = p2;
}
}
}
Your answer
Follow this Question
Related Questions
i need to use the rotation value of the x axis on a camera 1 Answer
Isometric game camera limits 4 Answers
How to extend tree size to more than 200? 0 Answers
how to limit rotation 2 Answers
LookAt Limit Up and Down rotation only 2 Answers