I'm working on an action game using the Phaser framework, and I want the player to be able to touch certain switch tiles to turn other enemies off and back on. So it should work like this:
I'm using arcade physics and the overlap function is working. But the problem is that the overlap keeps firing over and over again, like every single frame. What would be the best way in Phaser to get the desired result?
See screenshot below of what I mean, and I've created a sandox of my code example here: https://phaser.io/sandbox/edit/zEVOQfgA
Your code is not working because you are resetting okoverlap
to 0
on each update
. What you need to do is to set the okoverlap
to a state and change that state at suitable time.
I've fixed your code by saving the property in game
object in create
.
game.flags = {};
game.flags.okoverlap = 0;
Then in update
function I've checked that property and current overlap status.
function update() {
if(game.flags.okoverlap === 1 && !checkOverlap(mushroom, theswitch)) {
game.flags.okoverlap = 0;
}
game.physics.arcade.overlap(mushroom, theswitch, handleCollide, null, this);
}
function checkOverlap(spriteA, spriteB) {
var boundsA = spriteA.getBounds();
var boundsB = spriteB.getBounds();
return Phaser.Rectangle.intersects(boundsA, boundsB);
}
The logic inside handleCollide
function is changed to
if (game.flags.okoverlap != 1) {
game.flags.okoverlap = 1;
doSwitch();
}
Finally replace okoverlap
in render
with game.flags.okoverlap
to prevent ReferenceError
game.debug.text('overlap: ' + (game.flags.okoverlap == 1 ? 'YES': (game.flags.okoverlap == -1 ? 'partial': 'no')), 20, 40);
Working sample here - https://phaser.io/sandbox/edit/ikJBIznv
I've been playing around some more and found a solution, using 2 global variables. One variable frameoverlap
to check if there is an overlap, and one variable doswitch
to see if the switch action was already done. Then you can handle it all in the update() function.
function update() {
// assume no overlap
frameoverlap = 0;
// do arcade.overlap
game.physics.arcade.overlap(mushroom, theswitch, handleCollide, null, this);
// check flags after arcade.overlap
if (frameoverlap == 1) {
if (doswitch == 0) {
doswitch = 1; // remember the switch was done
doSwitch();
}
} else {
if (doswitch == 1) {
doswitch = 0; // stepping off the switch tile
}
}
}
See updated code here https://phaser.io/sandbox/edit/VTenTwgh
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.