Unity OnMouseDrag() Drag and Drop

16,039

Your z should be the distance from the camera: z=(Camera.main.transform.position-gameObject.transform.position).magnitude. Even with this it is possible that you will experience some drift because of float precision issues (depends on scale and luck).

If you will have drift problems, try to cache the z value.

Also, you would have more control (and no float drift problems) if you used Camera.main.ScreenPointToRay and raycasted that against a Plane:

Vector3 ScreenPosToWorldPosByPlane(Vector2 screenPos, Plane plane) {
    Ray ray=Camera.main.ScreenPointToRay(new Vector3(screenPos.x, screenPos.y, 1f));
    float distance;
    if(!plane.Raycast(ray, out distance))
        throw new UnityException("did not hit plane", this);
    return ray.GetPoint(distance);
}

The Plane used there should be something like this:

Plane plane=new Plane(Vector3.up, Vector3.zero);

It's oriented in the position Vector3.zero and it's facing upward (Vector3.up).

Share:
16,039
Tommy J
Author by

Tommy J

Updated on June 04, 2022

Comments

  • Tommy J
    Tommy J almost 2 years

    Trying to drag and drop a game object on the x and y axis. For some reason the values of x, y, and z get smaller as time goes on even if the mouse isn't moving. Can anyone explain why this is happening?

    using UnityEngine;
    using System.Collections;
    
    public class Drag : MonoBehaviour {
    
        Vector3 point;
        float x;
        float y;
        float z;
    
        void Update () {
    
        }
    
        void OnMouseDrag()
        {
            x = Input.mousePosition.x;
            y = Input.mousePosition.y;
            z = gameObject.transform.position.z;
    
            point = Camera.main.ScreenToWorldPoint (new Vector3 (x, y, z));
            gameObject.transform.position = point;
    
            Debug.Log ("x: " + point.x + "   y: " + point.y + "   z: " + point.z);
        }
    }
    
  • Tommy J
    Tommy J almost 10 years
    Can you point me to any good tutorials on how to use ray casting against a plane?
  • Krzysztof Bociurko
    Krzysztof Bociurko almost 10 years
    Edited my answer with an example.