hi guys, I’m quite new in unity and I’m stuck on controlling camera movement by player. As an exercise I’m creating kind of RTS game where player can move a camera above the map using W S A D and controlling camera rotation when holding right mouse button and move mouse.
For this I created empty game object which is followed by camera, user is moving this object using WSAD.
I’m trying to limit movement of this object between 0 and 1000 on X and Z axis, but I’m struggling with that if player rotate this object to any other angle
I’ve created 4 objects with BoxCollider on each edge, but I’m having problem write a script to prevent user to leave that area.
Not sure if that’s even right direction or is there any better way for this?
Before adding BoxColliders I was trying to calculate box position and prevent update if new X or Z position is outside boundary, which was working fine if I’m facing ‘Forward’, but once turn camera 90 or 180 degree when WSAD is moving oposit direction this kind of script doesn’t work anymore
My script
private void Update()
{
_horizontalInput = Input.GetAxis("Horizontal");
_verticalInput = Input.GetAxis("Vertical");
_mouseXInput = Input.GetAxis("Mouse X");
_mouseYInput = -Input.GetAxis("Mouse Y");
_rightMouseBtnClicked = Input.GetMouseButton(1);
// rotate camera with mouse when right mouse button is hold
if (_rightMouseBtnClicked)
{
// rotate camera horizontally
transform.Rotate(Vector3.up * Time.deltaTime * _cameraSpeed * _mouseXInput);
}
Vector3 vectRight = Vector3.right * Time.deltaTime * _cameraSpeed * _horizontalInput;
Vector3 vectForward = Vector3.forward * Time.deltaTime * _cameraSpeed * _verticalInput;
Vector3 _boxNewPos = vectRight + vectForward;
float posX = transform.position.x;
float posZ = transform.position.z;
float deltaX = posX + _boxNewPos.x;
float deltaZ = posZ + _boxNewPos.z;
Debug.Log(deltaX + " " + deltaZ);
Debug.Log(posX + " " + posZ);
if (deltaX < posX && posX > 100)
{
transform.Translate(new Vector3(_boxNewPos.x, 0, 0));
}
if (deltaX > posX && posX < 800)
{
transform.Translate(new Vector3(_boxNewPos.x, 0, 0));
}
if (deltaZ < posZ && posZ > 100)
{
transform.Translate(new Vector3(0, 0, _boxNewPos.z));
}
if (deltaZ > posZ && posZ < 800)
{
transform.Translate(new Vector3(0, 0, _boxNewPos.z));
}
}