Click GameObject and move

Hi all!
Fist of all I would like to say that I’m completely new in Unity. I’m a professional JavaScript and PHP programmer but for a purpose of creating a website for one of mine clients I needed a tool for creating 3D application for web. Unity is a PERFECT tool for it :slight_smile:

So my problem (or question) is: is it possible to click on some gameobject in a scene, and then move it to another position during runtime?

I tried to find an answer, but had no luck.

Is there any tutorial, script or example available about this?
If not, can anyone point to me how to catch Object name or tag during runtime?

To detect that the mouse is over an object, it must have a collider, or a GUI Element.

Read the basics first : Unity - Scripting API:

That was fast!
:slight_smile:
Thank you.

you can also add a rigidbody to your gameobject and the dragrigidbody script. you can drag your gameobject with the mouse over the scene.

I made it this way:

  • at the GameObject add boxcollider
  • create new script (as follows) and add it to the same GameObject
function Update () {

}

function OnMouseDrag () {
var speed = 0.2;
var x = Input.GetAxis("Mouse X") ;
var z = Input.GetAxis("Mouse Y") ;
this.transform.localPosition.x +=x*speed;
this.transform.localPosition.z +=z*speed;

if (Input.GetKeyDown(KeyCode.R))
	{
		this.transform.Rotate(0, 5, 0);
	}
if (Input.GetKeyDown(KeyCode.T))
	{
		this.transform.Rotate(0, -5, 0);
	}
   
}

It works, but I would like to know is this proper way?

I’m asking this because I will need to have instances of various GameObjects, so I will need to add that script to each of them. Will this be the proper way or is there another, better way to do this?

The Mouse X and Mouse Y input axes are actually mouse deltas, which means the amount the mouse has moved since the last frame rather than its absolute position. It is likely that the object being dragged will not move at the same speed as the mouse and this might look a bit strange. A good way to go is to move the object in the camera’s viewport space using the current mouse position:-

var camDist: float;

function OnMouseDown() {
	camDist = Camera.main.WorldToViewportPoint(transform.position).z;
}

function OnMouseDrag() {
	var viewPt = Camera.main.ScreenToViewportPoint(Input.mousePosition);
	viewPt.z = camDist;
	transform.position = Camera.main.ViewportToWorldPoint(viewPt);
}