![](/img/trans.png)
[英]Phaser - How to properly implement Arcade Physics Collisions with Phaser.js
[英]how can I change velocity of a child of a physics.group in phaser.js?
玩家必须接住鸡蛋,所以鸡蛋(由gameState.eggs = this.physics.add.group();
制成)在坡道上具有一定的velocity
,但是一旦它们离开坡道,我想要将 x setVelocity()
自动设置为 0,而不是只在屏幕上拍摄。
这是我的鸡蛋生成 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);
}
最后一个条件是我希望能发挥作用的,但它什么也没做。 澄清一下,在eggGen
this.time.addEvent();
在不知道整个代码(并假设使用街机物理)的情况下,我会说:
只需检查update
function,如果鸡蛋“在坡道上”和/或x 速度为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;
}
});
// ...
}
这是一个迷你演示:
如何做到这一点,它只涵盖了基础知识。
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.