Question by
TrinityNeo · May 25, 2019 at 10:12 PM ·
mousedrag objects
Drag Object Issues
Ok so I got this script to drag an object w/ the mouse, the drag part works, but the object can be dragged thru the floor, how to fix it?`
A tutorial can be found at this link: https://youtu.be/NMt6Ibxa_XQ
Also I added a floor to the project the tutorial doesn't have one. So you may have to add one if you set up this project. And one more thing, how to include the saved scene in this message so you can just open it and look at it directly instead of sending over the code sample etc.
using UnityEngine; using System.Collections;
public class drag : MonoBehaviour { Vector3 dist; float posX; float posY;
void OnMouseDown(){
dist = Camera.main.WorldToScreenPoint(transform.position);
posX = Input.mousePosition.x - dist.x;
posY = Input.mousePosition.y - dist.y;
}
void OnMouseDrag(){
Vector3 curPos = new Vector3(Input.mousePosition.x - posX, Input.mousePosition.y - posY,
dist.z);
Vector3 worldPos = Camera.main.ScreenToWorldPoint(curPos);
transform.position = worldPos;
}
}`
Comment