unity script for dragable object in javascript

Here is a sample script in javascript for dragging an object in Unity:

index.tsx
#pragma strict

private var isDragging: boolean = false;
private var startPos: Vector3;
private var offset: Vector3;

function OnMouseDown() {
    offset = gameObject.transform.position - Camera.main.ScreenToWorldPoint(Input.mousePosition);
    isDragging = true;
}

function OnMouseUp() {
    isDragging = false;
}

function Update() {
    if(isDragging) {
        var currentPos = Camera.main.ScreenToWorldPoint(Input.mousePosition) + offset;
        transform.position = Vector3(currentPos.x, currentPos.y, 0);
    }
}
522 chars
22 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.
  • Finally, 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