Drag and drop UI Objects

I’m trying to create a mechanic for players to click on a UI object and dragging and dropping it onto an objective. While I managed to get the object to move based on mouse movement, it simply moves much further than the cursor.

// Code Below
var MainInput = pc.createScript(‘mainInput’);

// initialize code called once per entity
MainInput.prototype.initialize = function() {
// check for touch input
this.touch = this.app.touch;
// obtain touch events if touch is present
if(this.touch){
this.touch.on(pc.EVENT_TOUCHSTART, this.onStart, this);
this.touch.on(pc.EVENT_TOUCHMOVE, this.onMove, this);
this.touch.on(pc.EVENT_TOUCHEND, this.onRelease, this);
console.log(“Taking touch events!”);
}
// obtain mouse events otherwise
else{
this.app.mouse.on(pc.EVENT_MOUSEDOWN, this.onStart, this);
this.app.mouse.on(pc.EVENT_MOUSEMOVE, this.onMove, this);
this.app.mouse.on(pc.EVENT_MOUSEUP, this.onRelease, this);
console.log(“Taking mouse events!”);
}
this.cursorPos = pc.Vec3.ZERO;
};

// update code called every frame
MainInput.prototype.update = function(dt) {

};

// touch event listeners
MainInput.prototype.onStart = function(event) {
if(this.touch){
//console.log(event);
}
else{
console.log(“Click”);
}
};

MainInput.prototype.onMove = function(event) {
var cameraEntity = this.app.root.findByName(‘Camera’);
if(this.touch){
// translate touch position into world position
cameraEntity.camera.screenToWorld(event.touches[0].x, event.touches[0].y, 1, this.cursorPos);
}
else {
// translate cursor position into world position
cameraEntity.camera.screenToWorld(event.x, event.y, 1, this.cursorPos);
}
console.log(this.cursorPos);
};

MainInput.prototype.onRelease = function(event) {

};

Maybe this will help?

3 Likes

you’re amazing thank you for this

1 Like