I'm making a game in Phaser which looks like that:
player has to catch the eggs, so the eggs (which are made from gameState.eggs = this.physics.add.group();
) have a certain velocity
while on the ramp, but then once they're off the ramp, i want to authomatically setVelocity()
to one with 0 for x coordinate, instead of just shooting across the screen.
Here's my egg generating function:
function eggGen() {
let num = Math.random();
let xCoord, yCoord, eggDirection, eggAnimation, velocityX
if (num < .5) {
xCoord = 100;
eggDirection = 'eggLeft';
eggAnimation = 'rollingLeft'
velocityX = this.velocityX;
if (num < .25) {
yCoord = 232;
} else {
yCoord = 382;
}
} else {
xCoord = 700;
eggDirection = 'eggRight';
eggAnimation = 'rollingRight';
velocityX = -(this.velocityX)
if (num < .75) {
yCoord = 232;
} else {
yCoord = 382;
}
}
let egg = gameState.eggs.create(xCoord, yCoord, eggDirection).setVelocity(velocityX, this.velocityY).setScale(.6);
if (egg.x > 220 && egg.x < 580) {
egg.setVelocity(0, this.velocityY);
}
egg.anims.play(eggAnimation);
}
the last conditional is what i hoped would do the magic, but it doesn't do anything. To clarify, eggGen
function is called inside this.time.addEvent();
Without knowing the whole code (and assuming arcade physics is used) , I would say:
Just check on the update
function, if a egg is "on the ramp" and/or has a x-velocity of 0
function update(){
// ...
gameState.eggs.getChildren().forEach(egg => {
if(egg.velocity.x > 0 && (egg.x > 220 || egg.x < 580)) {
// ... stop velocity.x or set the whole velocity new
egg.velocity.x = 0;
}
});
// ...
}
Here a mini Demo:
How one could do this, it just covers the basics.
document.body.style = 'margin:0;'; var config = { type: Phaser.AUTO, width: 300, height: 183, physics: { default: 'arcade', arcade: { debug: true, } }, scene: { create, update }, banner: false }; let objectGroup; function create () { objectGroup = this.physics.add.group(); this.time.addEvent({ delay: 500, callback: createObject, callbackScope: this, loop: true }); } function createObject(){ let spawnLeft = Phaser.Math.Between(0, 1); let obj = this.add.rectangle(spawnLeft? 0: config.width, 0, 10, 10, 0xff0000); this.physics.add.existing(obj); objectGroup.add(obj); obj.body.setVelocity((spawnLeft? 1: -1) * 75, 30); } function update(){ if(;objectGroup) return. objectGroup.getChildren().forEach(obj =>{ if(obj.body.velocity.x > 0 && (obj.x > 100 && obj.x < 150) || (obj.x > config.width - 150 && obj.x < config,width - 100) ){ // Just to keep the same speed. even after changing direction let speed = obj.body.velocity;length(). obj.body.velocity;x = 0. obj.body.velocity;y = speed; } }). } new Phaser;Game(config)
<script src="https://cdn.jsdelivr.net/npm/phaser@3.55.2/dist/phaser.js"></script>
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.