- Home /
Dragging Camera Speed
I'm making a strategy game and I would like the player to be able to drag the camera by clicking on the background and moving the cursor. I have the dragging functionality implemented but I'm having trouble getting the camera to move at the same speed as the cursor. The functionality I want is that when speed = 1.0, the camera moves at the same speed as the cursor. The user can then customize the scroll speed in the settings.
void Update()
{
if (mouseDown)
{
// Get the current mouse
Vector2 currentMouse = Input.mousePosition;
// Calculate delta
Vector2 delta = Camera.main.ScreenToWorldPoint(-oldMouse) + Camera.main.ScreenToWorldPoint(currentMouse);
print(delta);
Vector3 dV = new Vector3(delta.x * speed, 0, delta.y * speed);
// Move the camera
Camera.main.transform.position += dV;
oldMouse = currentMouse;
}
}
You are close here. When dealing with perspective and tracking, you have to say how far in front of the camera. In particular, when you call ScreenToWorldPoint(), the 'Z' parameter should be the distance in front of the camera.
if you want you can do it in a different way. in the OnGUI
if(Event.current.type == EventType.mouseDrag ) {
Camera.transform.Translate(new Vector3(Event.current.delta.x *-1,Event.current.delta.y ,0) * Time.deltaTime * factor);
}
you just have to change the factor value to change the speed
Answer by amphoterik · Jun 26, 2013 at 12:01 PM
The mouse input is always given in delta (that is, the amount it has changed since last frame). Therefore, moving the map is easy:
float dx = Input.GetAxis("Mouse X");
float dy = Input.GetAxis("Mouse Y");
And then moving the ground by that much. The problem stems from the fact that your ground is a distance away and you are probably in perspective mode. That will make the ground seem slower. What you need to do is determine a coefficient by which the ground at a certain distance will move at the same speed as the mouse. This is a trial and error thing.
If your camera can be at different distances from the ground, then you will need to know different values for the distance.
Now, you seem to be doing a lot of that already (kind of makes my rant moot, but alas). The main difference though, is that you want to user to be able to change it, but you also will need a speed coefficient. That again is easy to do. You will just need to make sure your coefficient brings your terrain up to 1:1 speed and then your speed reduces or increases it from there:
//my style from above
float dx = Input.GetAxis("Mouse X");
float dy = Input.GetAxis("Mouse Y");
Vector3 dV = new Vector3(-dx * coef * speed, 0, dy * coef * speed);
//your style
Vector3 dV = new Vector3(-delta.x * coef * speed, 0, delta.y * coef * speed);
The minus was also added to make it pan in the correct direction.