How do I make a camera controller where I can click and drag the world around, regardless of what angle the camera is at?
I am making an isometric game, and I want the player to be able to click on a point on the screen, and effectively drag that point (and the rest of the world) around with it on the x and z-axis. Obviously, I want to move the camera, and not the world. The problem I have is I can't find a solution that works if the camera has a somewhat random rotation.
If I did a bad job of explaining the desired effect, think of mobile games like Clash of Clans or My Singing Monsters where the user clicks on the screen and drags the view around.
I have been looking for an answer on a few sites, but have only found the following script that only works if the camera has 0 rotation:
public class CameraController : MonoBehaviour
{
private bool bDragging;
private Vector3 oldPos;
private Vector3 panOrigin;
private float panSpeed = 10;
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
bDragging = true;
oldPos = transform.position;
panOrigin = Camera.main.ScreenToViewportPoint(Input.mousePosition); //Get the ScreenVector the mouse clicked
}
if (Input.GetMouseButton(0))
{
Vector3 pos = Camera.main.ScreenToViewportPoint(Input.mousePosition) - panOrigin; //Get the difference between where the mouse clicked and where it moved
transform.position = oldPos + -pos * panSpeed; //Move the position of the camera to simulate a drag, speed * 10 for screen to worldspace conversion
}
if (Input.GetMouseButtonUp(0))
{
bDragging = false;
}
}
}
Comment