I'm brand new at this Unity business and am just messing around with dragging objects and making them react to being "let go" and continue moving at the velocity of the drag. I found this thread: http://answers.unity3d.com/questions/4898/drag-gameobject-with-mouse which seems to do what I want but there's a lot I don't understand about it.
I set up a little game board with a top-down camera view and attached the DragRigidbody script to a sphere object. It works great for moving around the sphere, but I noticed that when I drag it nearer to the edges of the game screen the Y position of the sphere increases, as if I'm pulling the sphere up.
My question is: how can I modify the code to ONLY use the X and Z positioning of the mouse to determine the drag? In other words, I want the dragged object to stay on a 2D plane.
Some searching has led me to think that this is where the code needs to be changed (although I might be wrong):
while (Input.GetMouseButton (0))
{
var ray = mainCamera.ScreenPointToRay (Input.mousePosition);
springJoint.transform.position = ray.GetPoint(distance);
yield;
}
I know that Input.mousePosition gives me the coordinates of the mouse in 2 dimensions, so why am I still getting vertical movement?
Consider you camera to be a point in space. You are using a fixed distance around this point to generate rays. This gives you a sphere around that point.
Perspective cameras are projected according to their projection matrix (which is determined by their field of view) which will determine the skew of the view frustum and consequently a skew on the camera projection generated by ScreenPointToRay.
To get a plane parallel to the clip plane of the camera, you would either have to use an orthographic camera or use ScreenToWorldPoint with a fixed z coordinate.
If you were to change your code to this, it should give you motion along a plane parallel to the camera clip planes:
while (Input.GetMouseButton (0))
{
var point = Input.mousePosition;
point.z = distance;
springJoint.transform.position = mainCamera.ScreenToWorldPoint(point);
yield;
}
Skovacs1's answer worked but I thought I'd share the modified code here for others to see:
var castedPlane : Plane = new Plane(Vector3.up, Vector3.zero);
...
var ray = mainCamera.ScreenPointToRay (Input.mousePosition);
//Start of the funky code
var ent : float = 100.0;
if (castedPlane.Raycast(ray, ent)){
var hitPoint = (ray.GetPoint(ent) - Vector3(0, 1, 0));
go.transform.position = hitPoint;
}
//End funky code
yield;
Where "go" is the object in question that I wanted to drag around (actually it was the Rigidbody dragger as referenced in DragRigidbody.js). Still had to subtract some height from the "hitpoint" in order for the object to go where I wanted (I think this is because the raycast is hitting the object's top, floating the true value upwards).