- Home /
Moving GameObjects with Mouse
Hallo!
How can I move an object (a cube for example) to a certain target point by clicking on the object and holding down the left mouse button?
Main idea is to move certain objects to their correct places.
Thanks in advance
Maria
Answer by Tseng · Oct 05, 2011 at 08:36 PM
I've used this one to move a crosshair in a 2.5D game.
It's a bit more complex, but it has two important things in it
It correctly accounts for the offset (depending on where you touch, other scripts will place the object below your mouse cursor), so that the object is moved correctly instead of it's origin being placed below the mouse cursor
It also has input touch, if you use it on Android/iPhone which doesn't react on OnMouseXXX Events
You can remove the Input parts of the controls, if you don't need them.
using UnityEngine;
using System.Collections;
public class MoveObjectScript : MonoBehaviour {
private Vector3 screenPoint;
private Vector3 offset;
private Vector3 curScreenPoint;
void Update() {
if(Input.touchCount==1) {
Touch touch = Input.touches[0];
Ray ray = Camera.main.ScreenPointToRay(touch.position);
RaycastHit rayHit = new RaycastHit();
bool isOverCrosshair = false;
if(Physics.Raycast(ray, out rayHit, 20.0f, layer)) {
isOverCrosshair = rayHit.transform.name=="Crosshair";
}
switch(touch.phase) {
case TouchPhase.Began:
if(isOverCrosshair)
OnMouseDown();
break;
case TouchPhase.Canceled:
case TouchPhase.Ended:
if(bMouseDown)
OnMouseUp();
break;
case TouchPhase.Moved:
OnMouseDrag();
break;
default:
break;
}
}
}
void OnMouseDown() {
Vector3 position = Vector3.zero;
if(Input.touchCount>0) {
position = new Vector3(Input.touches[0].position.x, Input.touches[0].position.y, 0);
} else {
position = Input.mousePosition;
}
// get the start position
screenPoint = Camera.main.WorldToScreenPoint(transform.position);
// calculate the offset from the click point to the center of the cross hair
offset = transform.position - Camera.main.ScreenToWorldPoint(
new Vector3(position.x, position.y, screenPoint.z));
}
void OnMouseDrag() {
// calculate new position
Vector3 position = Vector3.zero;
if(Input.touchCount>0) {
position = new Vector3(Input.touches[0].position.x, Input.touches[0].position.y, 0);
} else {
position = Input.mousePosition;
}
curScreenPoint = new Vector3(position.x, position.y, screenPoint.z);
transform.position = Camera.main.ScreenToWorldPoint(curScreenPoint) + offset;
// The above one is for a 2D/2.5D game, where the object will be drag in x and y positon, but be locked on z position.
// For full 3d movement, use this line instead
// transform.position = Camera.main.ScreenToWorldPoint(position) + offset;
}
}
Your answer
Follow this Question
Related Questions
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
Goes faster when moving to monster's transform 1 Answer
I get errorsfor my Click to Move Script 0 Answers
movement script 2 Answers
Hit problem unity 1 Answer