- Home /
Question by
xaxum_ · Sep 22, 2014 at 09:35 PM ·
mouse-drag
How to move object with mouse at same rate of mouse - 2D
I have a game gui text game object and I am trying to drag it with a mouse. However, when I click to drag the object it goes much faster than my mouse. I have the following code.
using UnityEngine;
using System.Collections;
public class DragIt : MonoBehaviour {
private Vector3 handleToOriginVector;
void OnMouseDown() {
handleToOriginVector = transform.root.position - Camera.main.ScreenToWorldPoint (Input.mousePosition);
}
void OnMouseDrag() {
transform.root.position = Camera.main.ScreenToWorldPoint (Input.mousePosition) + handleToOriginVector;
}
}
When I move mouse only a little the object moves in the direction of the mouse but much further than the mouse moves and keeps compounding the further I move. How can I make teh game object move with the mouse?
Comment
Best Answer
Answer by robertbu · Sep 22, 2014 at 09:37 PM
GUIText objects live in Viewport space, not world space. Change your ScreenToWorldPoint() calls to ScreenToViewportPoint() calls. Viewport space starts at (0,0) in the lower left of the screen and goes to (1,1) in the upper right.