- Home /
How to drag 3D game objects on X and Z axis? Keep Y axis constant
Hello, I'm trying to make a 3D Drag and drop system game and I want to move my object around X and Z axis only. I don't know how to make it work though. Could anyone help please?
public class DragAndDrop : MonoBehaviour
{
Vector3 offset;
public string destinationTag = "DropArea";
void OnMouseDown()
{
offset = transform.position - MouseWorldPosition();
transform.GetComponent<Collider>().enabled = false;
}
void OnMouseDrag()
{
transform.position = MouseWorldPosition() + offset;
}
void OnMouseUp()
{
var rayOrigin = Camera.main.transform.position;
var rayDirection = MouseWorldPosition() - Camera.main.transform.position;
RaycastHit hitInfo;
if (Physics.Raycast(rayOrigin, rayDirection, out hitInfo))
{
if (hitInfo.transform.tag == destinationTag)
{
transform.position = hitInfo.transform.position;
}
}
transform.GetComponent<Collider>().enabled = true;
}
Vector3 MouseWorldPosition()
{
var mouseScreenPos = Input.mousePosition;
mouseScreenPos.z = Camera.main.WorldToScreenPoint(transform.position).z;
return Camera.main.ScreenToWorldPoint(mouseScreenPos);
}
}
What if u use the y component of the mouse drag and place it to the z axis of the transform component?
Answer by Jellogramming · Mar 30 at 11:50 PM
If your object has a rigidbody, then you can go into "Constraints" and check the Y box for "Freeze position". If it doesn't have a rigidbody, then this could work:
float y;
void Start(){
y = transform.position.y;
}
void Update(){
Vector3 pos = transform.position;
pos.y = y;
transform.position = pos;
}
Hope this helps!
Your answer
Follow this Question
Related Questions
how to only get the negative or positive part of a GetAxis 1 Answer
Drag-and-drop gameObject inversely proportional to mouse speed? 0 Answers
Mouse Axis in 3D Space based on RaycastHit normal? 0 Answers
3d car left and right touch input 2 Answers
Where can I find resources on how to drag 3D objects into a room based on a grid 0 Answers