5

I started to create simple js game using pixijs. I need drag'n'drop functionality for Graphics circle but can't find info for this. I see only this example with sprites.

mtkachenko
  • 5,389
  • 9
  • 38
  • 68

2 Answers2

10

Drag + drop works the same way for both graphics and sprites.

var renderer = PIXI.autoDetectRenderer(800, 600, { antialias: true });
document.body.appendChild(renderer.view);

var stage = new PIXI.Container();    
stage.interactive = true;

var graphics = new PIXI.Graphics();
graphics.interactive = true;
graphics.lineStyle(0);
graphics.beginFill(0xFFFF0B, 0.5);
graphics.drawCircle(0, 0, 60);
graphics.endFill();
graphics.x = 100;
graphics.y = 100;
stage.addChild(graphics);    

// setup events
graphics
    .on('mousedown', onDragStart)
    .on('touchstart', onDragStart)
    .on('mouseup', onDragEnd)
    .on('mouseupoutside', onDragEnd)
    .on('touchend', onDragEnd)
    .on('touchendoutside', onDragEnd)
    .on('mousemove', onDragMove)
    .on('touchmove', onDragMove);

function onDragStart(event)
{
    // store a reference to the data
    // the reason for this is because of multitouch
    // we want to track the movement of this particular touch
    this.data = event.data;
    this.alpha = 0.5;
    this.dragging = true;
}

function onDragEnd()
{
    this.alpha = 1;

    this.dragging = false;

    // set the interaction data to null
    this.data = null;
}

function onDragMove()
{
    if (this.dragging)
    {
        var newPosition = this.data.getLocalPosition(this.parent);
        this.position.x = newPosition.x;
        this.position.y = newPosition.y;
    }
}

// run the render loop
animate();

function animate() {

    renderer.render(stage);
    requestAnimationFrame( animate );
}
Karmacon
  • 3,128
  • 1
  • 18
  • 20
  • Thanks for the answer. I implemented very similar approach. About drop zone: if I want to know when one circle is above another circle. It looks like I need to use contains method of Circle class. Right? – mtkachenko Apr 19 '16 at 09:48
  • 5
    Why didn't you link your source? http://scottmcdonnell.github.io/pixi-examples/index.html?s=demos&f=dragging.js&title=Dragging – Neuron Feb 24 '19 at 15:56
1

You also need to give hitArea for that circle to be able to attach mouse events to it. Read This Answer by GoodBoyDigital.

Santrro
  • 58
  • 7