I am trying to create a polygon dropzone and can’t seem to figure it out, any help would be greatly appreciated.
I’ve attached my code below which is a modified version of the dropzone example on labs.phaser.io. You should be able to copy and paste the code into Phaser 3 Examples to see it in action. If you look at the console logs it is hitting the hitAreaCallback function with every mouse move. Should it be doing that, or should that only be called when dropping or at the maximum while you are dragging?
var config = {
type: Phaser.AUTO,
parent: 'phaser-example',
width: 800,
height: 600,
scene: {
preload: preload,
create: create
}
};
// hitAreaCallback to determine if point is in polygon
function insidePolygon(polygon, x, y, gameObject) {
console.log("game object");
console.log(gameObject);
// ray-casting algorithm based on
// https://wrf.ecse.rpi.edu/Research/Short_Notes/pnpoly.html/pnpoly.html
console.log(polygon.geom.points);
console.log(x,y);
var vs = polygon.geom.points;
var inside = false;
for (var i = 0, j = vs.length - 1; i < vs.length; j = i++) {
var xi = vs[i].x, yi = vs[i].y;
var xj = vs[j].x, yj = vs[j].y;
var intersect = ((yi > y) != (yj > y))
&& (x < (xj - xi) * (y - yi) / (yj - yi) + xi);
if (intersect) inside = !inside;
}
console.log("in polygon", inside);
return inside;
};
var game = new Phaser.Game(config);
function preload ()
{
this.load.atlas('cards', 'assets/atlas/cards.png', 'assets/atlas/cards.json');
}
function create ()
{
// Create a stack of random cards
var frames = this.textures.get('cards').getFrameNames();
var x = 100;
var y = 100;
for (var i = 0; i < 64; i++)
{
var image = this.add.image(x, y, 'cards', Phaser.Math.RND.pick(frames)).setInteractive();
this.input.setDraggable(image);
y += 6;
}
// POLYGON DROPZONE CODE HERE
var color = new Phaser.Display.Color();
color.random(50);
var polygon = [{"x":203,"y":369},{"x":200,"y":380},{"x":204,"y":391},{"x":185,"y":389},{"x":138,"y":417},{"x":148,"y":445},{"x":201,"y":435},{"x":226,"y":370}];
var shape = this.add.polygon(300,0,polygon).setFillStyle(color.color);
var zone = this.add.zone(0, 0, 100, 100)
.setName("dropzone")
.setDropZone(shape, insidePolygon);
// END CODE HERE
this.input.on('dragstart', function (pointer, gameObject) {
this.children.bringToTop(gameObject);
}, this);
this.input.on('drag', function (pointer, gameObject, dragX, dragY) {
gameObject.x = dragX;
gameObject.y = dragY;
});
this.input.on('drop', function (pointer, gameObject, dropZone) {
gameObject.x = dropZone.x;
gameObject.y = dropZone.y;
gameObject.input.enabled = false;
});
this.input.on('dragend', function (pointer, gameObject, dropped) {
if (!dropped)
{
gameObject.x = gameObject.input.dragStartX;
gameObject.y = gameObject.input.dragStartY;
}
});
}