I am new to unity and game programming and am trying to get a basic script working from googling and searching the documentation.
I have wrote a script which i applied to main camera as a component, there are no syntax errors but when i run the game i do not get the expected behavior and am out of guesses on what i did wrong.
Simply i am trying to move the camera on the X & Y axis with a right click and drag motion of the mouse with a script but it did not work.
This is my script attempt, perhaps some one can see my mistake:
using UnityEngine;
using System.Collections;
public class cameraMove : MonoBehaviour {
// VARIABLES
public float panSpeed = 4.0f;
private Vector3 mouseOrigin;
private bool isPanning;
// Update is called once per frame
void Update ()
{
mouseOrigin = Input.mousePosition;
if (Input.GetMouseButtonDown (1))
{
//right click was pressed
isPanning = true;
}
// cancel on button release
if (!Input.GetMouseButton (1))
{
isPanning = false;
}
//move camera on X & Y
if (isPanning)
{
Vector3 pos = Camera.main.ScreenToViewportPoint (Input.mousePosition - mouseOrigin);
// update x and y but not z
Vector3 move = new Vector3 (pos.x * panSpeed, pos.y * panSpeed, 0);
Camera.main.transform.Translate (move, Space.Self);
}
}
}
It seems you are setting your mouseOrigin variable every Update() instead of setting it once when the mouse is first clicked. That would make the line:
@Doodums
I know that this is an old post, but could you explain what this code does? I’m new to programming, and just want some information on mouse position. Thanks!
But with that solution the dragging speed is set by a multiplicator, so the mouse pointer stays not on top of the point in 3d space to the time it was clicked.
Wondering if there is a solution where after every frame of camera dragging the same spot in 3d space is below the mouse pointer. That behaviour would feel way more comfortable. With the above solution the cam movement tends to be to slow or to fast, it’s not possible to adjust it to the exact movement of the mouse.