Here is a sample script in javascript for dragging an object in Unity:
index.tsx522 chars22 lines
Explanation:
isDragging
is a boolean variable that tracks whether the object is being dragged or not.startPos
is the initial position of the object.offset
is the difference between the position of the mouse on screen and the position of the object in world space.OnMouseDown()
is called when the user clicks on the object. It sets offset
to the difference between the mouse position and the position of the object and sets isDragging
to true.OnMouseUp()
is called when the user releases the mouse button. It sets isDragging
to false.Update()
is called every frame. If isDragging
is true, it updates the position of the object to the position of the mouse plus offset
.Vector3(currentPos.x, currentPos.y, 0)
is used to set the z-axis to 0 so that the object remains on the same plane as the UI.gistlibby LogSnag