Hello,
I am working on a 2d strategy game. In my first attempt for allowing the player to move the camera, movement was done by moving the mouse to the screen borders, which worked okay but wasn’t really what I had in mind. SO, now I am trying to make it so that the player can drag the mouse with pressed right mouse button in order to make the camera move over the map.
My code so far looks like this:
using UnityEngine;
using System.Collections;
using System;
public class CameraDragNDrop : MonoBehaviour {
bool dndActive = false;
private Vector3 lastMousePosition;
// TODO touchcapablefy this!
void Update () {
if (Input.GetMouseButton(1))
{
if (dndActive)
{
// continue drag'n'drop
Debug.Log("Continue dnd");
int time = Environment.TickCount;
Vector3 movement = Input.mousePosition - lastMousePosition;
Camera.main.GetComponent<Transform>().position -= movement / (Camera.main.orthographicSize*200);
Debug.Log((Environment.TickCount - time) + "ms for camera shift");
lastMousePosition = Input.mousePosition;
}
else
{
Debug.Log("Begin drag'n'drop");
// begin drag'n'drop
lastMousePosition = Input.mousePosition;
dndActive = true;
}
}
else if (dndActive)
{
// end drag'n'drop
dndActive = false;
}
}
}
The camera moves where I want it to go, but there is a tiny problem: Whenever the right mouse button is pressed, the framerate drops to ~1 to 3 fps (instead of ~50 immediately before). As soon as the RMB is released, it goes back up to 50 fps.
As you can see, I tried to measure the time taken by the camera transformation (around line 20), and according to my console, it takes only ~15ms, which doesn’t add up to the ~600ms a single iteration of the main thread takes according to the Unity statistics window.
Any ideas what I am doing wrong? I don’t really have a clue what could be the problem, my vector calculations shouldn’t take more than a couple of CPU cycles and moving the camera did not cause any problems in my previous script (where I also simply altered the transform.position of the camera using += or -=).
Thanks for your help!