How do I get how much Ive moved the mouse in X while holding the mouse button down? The code below just seem to be giving the speed at wich the mouse is moving.
For example, if I start to hold down the mousebutton and then move it some distance, I want that distance in the debug log and not the speed at wich I was moving it.
If you just want the “as the crow flies” delta for movement each frame, you need to store that information and increment it each frame.
var mouseDistance = 0;
private var lastPosition;
private var trackMouse = false;
function Update ()
{
if (Input.GetButtonDown ("Fire1"))
{
trackMouse = true;
lastPosition = Input.mousePosition;
}
if (Input.GetButtonUp ("Fire1"))
{
trackMouse = false;
Debug.Log ("Mouse moved " + mouseDistance + " while button was down.");
mouseDistance = 0;
}
if (trackMouse)
{
var newPosition = Input.mousePosition;
// If you just want the x-axis:
mouseDistance += Mathf.Abs (newPosition.x - lastPosition.x);
// If you just want the y-axis,change newPosition.x to newPosition.y and lastPosition.x to lastPosition.y
// If you want the entire distance moved (not just the X-axis, use:
//mouseDistance += (newPosition - lastPosition).magnitude;
lastPosition = newPosition;
}
}
@burnumd 's answer is a great way to show the total distance your mouse pointer “walked” on the screen in screen pixel coordinates (good solution!). But if what you need is just the distance between two points in 3D space, you will need another approach:
private var start: Vector3;
private var end: Vector3;
function Update(){
var hit: RaycastHit;
var distance: Vector3;
if (Input.GetMouseButtonDown (0)){
if (Physics.Raycast(camera.ScreenPointToRay(Input.mousePosition), hit)){
start = hit.point;
}
}
if (Input.GetMouseButtonUp (0)){
if (Physics.Raycast(camera.ScreenPointToRay(Input.mousePosition), hit)){
end = hit.point;
distance = end - start;
Debug.Log("Distance in X = "+Mathf.Abs(distance.x));
}
}
}
The distance variable holds the 3D distance between the points where you’ve pressed and released the left mouse button - actually, the points where an imaginary ray cast from the mouse pointer intercepted some collider. You can have the direct distance using distance.magnitude, or the distance measured in the X axis using distance.x