I have a Unity3D project. This project has a prefab I created (a table top) with a plane as the top of the able. The plane has a box colider and rigid body. On the table top, I have another object. I want to move this object only around the table top (X and Z axis). The object should never be raised above the table top. I have this code attached to my object:
void OnMouseDown()
{
Debug.Log("mouse down");
screenPoint = Camera.main.WorldToScreenPoint(transform.position);
offset = transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
}
void OnMouseDrag()
{
Debug.Log("mouse drag");
Vector3 curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint) + offset;
transform.position = curPosition;
}
This moves the object around but it also moves the object above the table top. Is there a way to keep the object on the table?
It sounds like what you're looking for is to project the mousePosition onto the table. The mousePosition is originally in the screen space (which it looks like you've recognised with ScreenToWorldPoint), and you need to find the location of the table it hits from the screen position.
Check out Physics.Raycast
Once you have that point, you can just set the transform of the object to that, though you may want to set the vertical component to a constant value for that object rather than the resulting value.
To do this, you may need to set the table to a collision layer (if you haven't already) and make sure you're looking for that only. Note that with Raycast, the layerMask is a register, represented by an int (i.e. [0 1 2..31]), so you use bitwise operations to select your layers e.g.
layerMask = (1<<LayerMask.NameToLayer("Table"))
Hope this helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With