Drag drop mechanics

var Touch = pc.createScript("touch");

// initialize code called once per entity
Touch.prototype.initialize = function () {
    this.pos = new pc.Vec3();
    this.cameraEntity = this.app.root.findByName("Camera");

    // Only register touch events if the device supports touch
    var touch = this.app.touch;
    if (touch) {
        touch.on(pc.EVENT_TOUCHSTART, this.onTouchStart, this);

    this.on('destroy', function () {
        if (touch) {
            touch.off(pc.EVENT_TOUCHSTART, this.onTouchStart, this);
    }, this);

Touch.prototype.updateFromScreen = function (screenPos) {
    // Use the camera component's screenToWorld function to convert the 
    // position of the mouse into a position in 3D space
    var depth = 20;
    this.cameraEntity.camera.screenToWorld(screenPos.x, screenPos.y, depth, this.pos);

    // Finally update the entity's world-space position

Touch.prototype.onTouchStart = function (event) {
    // Update the entity's position only when touched

In this line of code, there is an object on the screen and I want to drag and drop this object to a different place, but wherever I touch on the screen I touch it, how can I fix it.

Hi @Ozden_Delibas,

Is it possible to explain a bit more what you mean whenever I touch on the screen I touch it?

Given your code I think you first need some form of raycasting so you can select on the first touch the object to drag/drop. Check this example, on how to pick an object and place it somewhere on the world, it may be a good starting point:


1 Like


I have a game here. If you look at the mobile view, there is a button. When I press the button, it produces new pieces in the bottom 3 sections. I want to drag those pieces and drop them into one of the square areas, but I couldn’t.