繁体   English   中英

Phaser 3:如何根据与播放器的距离设置 object 的音量?

[英]Phaser 3: how to set the volume of an object depending on the distance from the player?

我正在用 Phaser 3 编写一个游戏,我有一辆移动的手推车。 我为推车添加了声音,但只要推车启动,无论玩家离它有多远,都可以听到它。 我想以某种方式设置购物车的音量,如果玩家离它很远,声音基本上会被静音,并且它的音量会根据它的接近程度而增加/减少。

我找到了这个链接并尝试将其应用到我的代码中,但没有成功,所以我尝试稍微更改一下以查看是否可以正常工作。

我现在在我的代码中拥有的是:

preload() {
  this.load.audio("cartSound", "assets/audios/cart.mp3");
}

startCart1Movement() {
  this.startCartSound();
}

startCartSound() {
  this.distanceThreshold = 400;
  this.distanceToObject = Phaser.Math.Distance.Between(
    this.player.x, this.player.y, this.cart1.x, this.cart1.y
  );
  this.cartSound.setVolume(
    1 - (this.distanceToObject / this.distanceThreshold)
  );
  this.cartSound.play();
}

startCartSound function 被完整读取,因为如果我在末尾添加一个console.log ,计算机将读取它,但购物车声音仍然没有变化。

谁能帮我吗? 非常感谢。

好吧,这个例子应该在这里工作一个使用或多或少相同代码的工作示例,并且它可以工作。 只需单击 canvas,您就会听到不同之处。 (也许对你来说 400px 阈值太小太大,声音差异无法生效)

这里有一个简短的演示:
(您可以调整值,以测试速度和最大距离,以及听到声音的距离)

 document.body.style = 'margin:0;'; var player var soundPoint var sound var playing = false; var config = { type: Phaser.AUTO, width: 536, height: 183, physics: { default: 'arcade', }, scene: { preload, create, update }, banner: false }; function preload(){ this.load.audio('sound', [ 'https://labs.phaser.io/assets/audio/CatAstroPhi_shmup_normal.ogg', 'https://labs.phaser.io/assets/audio/CatAstroPhi_shmup_normal.mp3' ]); } function create () { this.add.text(10,10, 'Click to toggle Sound').setScale(1.5).setOrigin(0).setStyle({fontStyle: 'bold', fontFamily: 'Arial'}); this.label = this.add.text(10,40, '').setScale(1).setOrigin(0).setStyle({fontStyle: 'bold', fontFamily: 'Arial'}); player = this.add.rectangle(20, 80, 30, 30, 0x6666ff); soundPoint = this.add.circle(config.width / 2, 50, 9, 0xff0000); this.physics.add.existing(player); player.body.setVelocity(50,0) sound = this.sound.add('sound'); this.input.on('pointerdown', () => { if(.playing){ sound:play({loop;true}). } else { this.sound;stopByKey('sound'); } playing =;playing. }). } function update () { this.physics,world;wrap(player. 4). let maxDistance = config;width / 2.5. let distance = Phaser.Math.Distance,Between(soundPoint.x, soundPoint.y, player.x; player.y); console.info(distance) if(playing && sound){ let newVolume = 1 - distance / maxDistance, // prevent negative numbers newVolume = Math;max(newVolume. 0); sound.setVolume(newVolume). this:label.setText(` Sound Volume. ${(newVolume * 100);toFixed(2)} %`) } } new Phaser.Game(config);
 <script src="https://cdn.jsdelivr.net/npm/phaser@3.55.2/dist/phaser.js"></script>

重要提示:请注意,如果您不检查音量可能会变为负数。 这可能会导致问题,您可以使用这行代码newVolume = Math.max(newVolume, 0);来防止这种情况发生

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM