Phaser3:检测精灵冲突

时间:2019-06-24 03:55:35

标签: javascript collision-detection phaser-framework

使用Phaser 3,我无法检测到两个精灵之间的碰撞。我在文档和几个示例中上下浮动,大多数都已经在Phaser 2中过时了,由于某种原因,它根本无法正常工作。

我要做的是一个 mapTiles 数组和一个 player 字符。现在,我已经将墙壁地板全部传递给对撞机,仅用于测试目的,什么也没发生。

正如您在下面的代码中看到的,我确实有一个对撞机正在使用 this.enemies 数组,因此我不确定为什么它不能与 this.mapTiles一起使用。另外,在检查我的 mapTiles 类型时,它们分别标记为 Sprite ,而我的敌人显然标记为 ArcadeSprite ,这可能是问题吗?

enter image description here

Dungeon.js

import 'phaser';

import {
  Enemy,
  MapGenerator,
  PlayerCharacter
} from '../game_objects/index'

class DungeonScene extends Phaser.Scene {
  constructor() {
    super({ key: 'DUNGEON' });
    this.mapTiles = []
    this.walls = []
    this.player = null
    this.enemies = []
    this.entities = []
  }

  preload() {
    this.load.spritesheet('sprites', 'src/arial10x10.png', { frameWidth: 10, frameHeight: 10 })
  }

  create() {
    this.createMap()
    this.player = new PlayerCharacter('PC', this, 9, 9, 'sprites', 32, { health: 100, atk: 10 }, [])
    this.enemies = [
      new Enemy('E1', this, 64, 64, 'sprites', 100, { health: 100, atk: 10 }, [])
    ]

    this.keyboard = this.input.keyboard.addKeys('W, A, S, D')

    // this works but not by default; aka it requires a callback to do anything
    // which is odd because examples show it working without a callback
    this.physics.add.collider(this.player, this.enemies, () => {
      this.scene.restart()
    })
    // DOES NOT WORK
    this.physics.add.overlap(this.player, this.mapTiles, () => console.log('overlap'))
    // DOES NOT WORK
    this.physics.add.collider(this.player, this.mapTiles, () => console.log('collider'))
  }

  createMap() {
    const mapGenerator = new MapGenerator(this, 39, 39, 9, 9)
    mapGenerator.create()
    this.mapTiles = mapGenerator.mapTiles
  }
}

编辑

我决定减少一些代码,并给出一个三行代码的示例,以说明不起作用。

这是只有两个精灵的一个,仍然无法正常工作。这个小例子将放在我的场景中 create 方法。

this.foo = this.add.sprite(10, 10, 'sprites', 32)
this.bar = this.add.sprite(30, 30, 'sprites', 2)
this.physics.add.collider(this.foo, this.bar)

1 个答案:

答案 0 :(得分:0)

碰撞不适用于您,因为精灵没有物理物体。

如您所述,mapTiles类型为Resume Next,其中敌人为Sprite,表示他们具有物理体。

创建它们的区别是使用的工厂。

ArcadeSprite使用GameObject工厂(精灵是GameObjects),this.add.sprite(...)使用物理Arcade工厂,该工厂创建一个精灵,并为其赋予物理实体。

因此,在用于最小示例的代码中,更改您创建精灵的调用以使用this.physics.add.sprite(...)与物理工厂一起使用,它应该可以工作。

我不知道您的地图生成器代码是什么样的,但我认为它将是类似的解决方法。

相关问题