Problem with pan and rotate camera with mouse
I created a script that rotates and pans the camera using the mouse. It's like an RTS style pan where if you move your mouse toward the edge of the screen, it'll pan the camera along the x and z axes. I also set it so that if you hold the right mouse button and drag, it'll rotate the camera.
However, the problem I'm having is that if I rotate the camera and then try to pan, then the panning is going the wrong direction. Since it's using the edge of the screen near the mouse pointer to detect where to move along the screen's x and y axes, then it'll always pan the screen up along the y axis when I put my pointer at the top of the screen. This doesn't work because I may have rotated the screen and y is no longer up.
Here's the code I'm currently using. Does anyone know how to make an adjustment to the code that detects my pointer location so that if I move the mouse to the sides of the screen, it'll always pan in the correct direction like most RTS games do?
using System; using UnityEngine;
public class CameraController : MonoBehaviour { public Vector3 newPosition;
public float panSpeed = 20f;
public float panBorderThickness = 10f;
public Vector2 panLimit;
public float scrollSpeed = 10f;
public float minY = 20f;
public float maxY = 120f;
private float mouseX;
public Vector3 rotateStartPosition;
public Vector3 rotateCurrentPosition;
private Quaternion newRotation;
void LateUpdate()
{
HandleMouseRotation();
Vector3 pos = transform.position;
if (Input.GetKey("w") || Input.mousePosition.y >= Screen.height - panBorderThickness)
{
pos.z += panSpeed * Time.deltaTime;
}
if (Input.GetKey("s") || Input.mousePosition.y <= panBorderThickness)
{
pos.z -= panSpeed * Time.deltaTime;
}
if (Input.GetKey("d") || Input.mousePosition.x >= Screen.width - panBorderThickness)
{
pos.x += panSpeed * Time.deltaTime;
}
if (Input.GetKey("a") || Input.mousePosition.x <= panBorderThickness)
{
pos.x -= panSpeed * Time.deltaTime;
}
float scroll = Input.GetAxis("Mouse ScrollWheel");
pos.y -= scroll * scrollSpeed * 100f * Time.deltaTime;
pos.x = Mathf.Clamp(pos.x, -panLimit.x, panLimit.x);
pos.y = Mathf.Clamp(pos.y, minY, maxY);
pos.z = Mathf.Clamp(pos.z, -panLimit.y, panLimit.y);
transform.position = pos;
mouseX = Input.mousePosition.x;
}
public void HandleMouseRotation()
{
var easeFactor = 10f;
if (Input.GetMouseButton(1))
{
Debug.Log("mousex stored: " + Input.mousePosition.x);
Debug.Log("mouseX: " + mouseX);
if (Input.mousePosition.x != mouseX)
{
var cameraRotationY = (Input.mousePosition.x - mouseX) * easeFactor * Time.deltaTime;
this.transform.Rotate(0, cameraRotationY, 0);
Debug.Log("rotationlog");
}
rotateStartPosition = Input.mousePosition;
Vector3 difference = rotateStartPosition - rotateCurrentPosition;
rotateStartPosition = rotateCurrentPosition;
newRotation *= Quaternion.Euler(Vector3.up * (-difference.x / 5f));
}
}
}