如何根据Phaser3中的条件更改组精灵的方向



我正在使用Phaser3并尝试这样做:

class Bee extends Phaser.GameObjects.Sprite {
constructor(config) {
super(config.scene, config.x, config.y, 'bee');
config.scene.add.existing(this);
config.scene.physics.add.existing(this);
this.initial = [config.x, config.y];
this.x = config.x;
this.y = config.y;
this.speed = 5;
}
preUpdate() {
if  (this.y < this.initial[1] - 100) {
this.speed *= -1;
}
if (this.y > this.initial[1] + 100) {
this.speed *= -1;
}
this.y += this.speed;
this.setY(this.y);
}
}

我希望Bee对象向下移动100像素,然后向上移动,然后重复,但它似乎不起作用。

在我的场景中,我创建了一个对象:

bees = this.physics.add.group();
let bee = new Bee({scene:scene, x: 100, y:200})
bee.setScale(0.5);
bee.allowGravity = false;
bees.add(bee);

我会在游戏中有多个蜜蜂精灵。

你可以用一个简单的tween来解决上下运动(https://photonstorm.github.io/phaser3-docs/Phaser.Tweens.Tween.html)
tween在起始位置和结束位置之间更改/移动所选属性(或多个属性(。在你的情况下,我会用它来改变蜜蜂物理体速度y特性。

你可以用tween做很多事情,而不需要计算速度、下一个位置等等。你只需要调整tween配置的属性,就可以获得所需的移动/动画

这里有一个工作示例:
(更新:现在组中有几只蜜蜂,飞行模式有一个"偏移"(

class Bee extends Phaser.GameObjects.Sprite {
constructor(config) {
super(config.scene, config.x, config.y, 'bee');
config.scene.add.existing(this);
config.scene.physics.add.existing(this);
this.x = config.x;
this.y = config.y;

config.scene.tweens.add({
targets: this.body.velocity,
y: { from: -100, to: 100  },
ease: Phaser.Math.Easing.Quadratic.InOut,
yoyo: true,
repeat: -1,
duraton: 1000,
// just to create a interesting offset for the example
delay: Phaser.Math.Between(0,6) * 200
});
}
}
function create(){
let bees = this.physics.add.group();
for(let i=0; i < 10 ; i++){
let bee = new Bee({scene: this, 
x: i * -100 , 
y: 50 });       
bees.add(bee);
}     
bees.setVelocity(100,0)
}
const config = {
type: Phaser.AUTO,
width: 400,
height: 200,
physics: {
default: 'arcade',
},
scene: {
create
}
};
const game = new Phaser.Game(config);
<script src="https://cdn.jsdelivr.net/npm/phaser@3.55.2/dist/phaser.js"></script>

最新更新