Calculating change in mouse position

Hi,

I want to be able to move an object based on the movement of my cursor. I don’t want it to be placed at the mouse position, or be directly dependent on it; instead I want it to move depending on the difference between the current mousePosition and the last mousePosition.

I am using this code to try to achieve this:

var cam : Camera;
var worldPos : Vector3;

function Update() {
var mousePos = Input.mousePosition;
mousePos.z = 125;
worldPos = cam.ScreenToWorldPoint(mousePos);
}

function LateUpdate() {
var mousePos2 = Input.mousePosition;
mousePos2.z = 125;
var worldPos2 = cam.ScreenToWorldPoint(mousePos2);
transform.position.x += worldPos2.x - worldPos.x;
}

But it doesn’t seem to work! :frowning: Any ideas what I’m doing wrong?

Thanks in advance. :slight_smile:

Update and Late update will give you the same positions. Try getting the mouse value one frame later so make your calculation, place the object and the store the mouse position and use it next time such as :

function Update() {

worldPos = cam.ScreenToWorldPoint(mousePos);
mousePos = Vector3(Input.mousePosition.x,Input.mousePosition.y,125);

}

Hope that is the answer you seek

This script will Debug the changes in the mouse position between frames when you click or hold the mouse button. These values are stored in delta.x and delta.y :

#pragma strict

public var delta : Vector3 = Vector3.zero;
private var lastPos : Vector3 = Vector3.zero;

function Update()
{
    if ( Input.GetMouseButtonDown(0) )
    {
        lastPos = Input.mousePosition;
    }
    else if ( Input.GetMouseButton(0) )
    {
        delta = Input.mousePosition - lastPos;

        // Do Stuff here
		
		Debug.Log( "delta X : " + delta.x );
		Debug.Log( "delta Y : " + delta.y );

        // End do stuff

        lastPos = Input.mousePosition;
    }
}