- Home /
On Mouse Drag Game Object follows Mouse on a single Axis.
Hello People,
I'm trying to create a 2d game and the game objects should follow the mouse on a single axis (the x axis), when the user drags the object.
Here's my code, the problem is, that the game object flies out of the screen as soon as i try to drag it, instead of following the mouse,
using UnityEngine; using System.Collections;
[RequireComponent(typeof(BoxCollider))]
public class MovePoint : MonoBehaviour
{ void OnMouseDrag() { Vector3 point = Camera.main.ScreenToWorldPoint(Input.mousePosition); point.y = gameObject.transform.position.y; gameObject.transform.Translate(point.x,0,0); Screen.showCursor = false; }
void OnMouseUp()
{
Screen.showCursor = true;
}
}
Help would be much appreciated.
Answer by loopyllama · Mar 10, 2011 at 03:07 PM
instead of gameObject.transform.Translate(... do a gameObject.transform.positon = point...or whatever you want to set it to.
Translate moves the object, at its current position, by some amount. You want to set the position to the position of the mouse so you can just set the position directly.
You should really cache the transform of the object in a start or awake function. check out caching in the docs.
Your answer
Follow this Question
Related Questions
Dragging camera around object using mouse issue 0 Answers
Lock main camera on x-axis 2 Answers
Drag and Drop w/ Snapping 0 Answers
Maintain x axis distance between a 2d rigidbody and mouse 1 Answer