How will i drag my object only x and y axis?

Hi All,

I am new to unity 3d. I have a stop watch.

My task is i want to drag my stop watch in the hole scene . I wrote the code for x,y axis moving of the stop watch. but that is not moving.

My code is:

using UnityEngine;
using System.Collections;

public class Moused : MonoBehaviour {
public float sensitivity = 0.02f;
private Vector3 v3Prev;
 
void OnMouseDrag () {
if (Input.GetMouseButtonDown(0)) {
v3Prev = new Vector3(Input.mousePosition.x,Input.mousePosition.y,0);
}
if (Input.GetMouseButton (0)) {
		    Vector3 newPos = transform.position;
newPos.x = newPos.x + (Input.mousePosition.x - v3Prev.x) * sensitivity;
newPos.y = newPos.y + (Input.mousePosition.y - v3Prev.y) * sensitivity;		
transform.position = newPos;
v3Prev = newPos;
}
}
}

I don’t know the problem for moving. i added box collider to the stop watch.

can i get a solution. or any help

Thanks&Regards

Shankar

As robertbu said, Input.mousePosition is in “screen space” but you want to drag in “world space”. Therefore:

using UnityEngine;
using System.Collections;

public class DragScript : MonoBehaviour {
	
	private Vector3 dragPosition;
	
	void OnMouseDrag()
	{
	    dragPosition = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 0);
		dragPosition = Camera.main.ScreenToWorldPoint(dragPosition);
		dragPosition.z = 0.0f; // assuming 2D game
	}
	
	void Update() {
		transform.position = dragPosition;
	}
}

I think the order of your code is illogical. Think about what you need to do step by step.
However as you’re new to Unity I think the function should look like this:

void OnMouseDrag()
{
    if (Input.GetMouseButtonDown(0))
    {
        // you have a vector 3 position
        v3Prev = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 0);
    }

void Update()
{
    // Do your gameobject movements here
    transform.position = v3Prev;
}

Assuming this script is attached to your object of course. This is untested as I am at work. Hope this helps