'Phaser 3 increase drag click area size of sprite
We have a sprite which we set as interactive
this.testSprite = this.add.sprite(100, 100, 'button')
.setInteractive();
Now we make this object draggable by adding
this.input.dragDistanceThreshold = 20;
this.input.setDraggable(this.testSprite);
this.input.on('drag', function (pointer, obj, dragX, dragY) {
obj.x = dragX;
obj.y = dragY;
});
Now if we want to increase the size of the draggable area (be able to click a little further to still drag the object), I tried giving the .setInteractive() function the additional parameter for the new bounds new Phaser.Geom.Rectangle(0, 0, 1000, 1000) such as:
this.testSprite = this.add.sprite(100, 100, 'button')
.setInteractive(new Phaser.Geom.Rectangle(0, 0, 1000, 1000));
It doesn't seem to affect this draggable property. Is this the proper way to do it or is there a separate drag size property that I can't find?
Solution 1:[1]
You can use the setInteractive method of the sprite, to define a valid hitArea, that is bigger than the "button", as requested. (here a link to the docs).
Just define a hitArea and a hitAreaCallback, and it should work.
(I using the Phaser builtin function to test it the point is in the hitArea, here the docs)
Here a working demo:
// Minor formating for stackoverflow
document.body.style = "display: flex;flex-direction: column;";
var config = {
type: Phaser.AUTO,
width: 536,
height: 183,
scene: {
create
}
};
function create () {
// Padding for the drag Area, just for the demo
let padding = 50;
let button = this.add.sprite(50, 50, 'button').setOrigin(0);
button.setInteractive({
draggable: true,
// SETUP hitarea
hitArea: new Phaser.Geom.Rectangle(
- padding,
- padding,
button.width + padding * 2,
button.height + padding * 2 ),
//Check hitarea
hitAreaCallback: function(hitArea, x, y){
return Phaser.Geom.Rectangle.Contains(hitArea, x, y);
}
});
// The following line, is not needed since this option is set in "setInteractive"
// this.input.setDraggable(button);
this.input.on('drag', function (pointer, obj, dragX, dragY) {
obj.x = dragX;
obj.y = dragY;
});
}
var game = new Phaser.Game(config);
<script src="//cdn.jsdelivr.net/npm/[email protected]/dist/phaser.min.js">
</script>
Info: This Demo doesn't load an real image, but the placeholder is draggable(with the padding), as nedede.
The hitArea is relative to the top left corner of the image, thats why the first two parameters, are negative.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
