【问题标题】:Phaser3: Detecting sprite collisionPhaser3:检测精灵碰撞
【发布时间】:2019-11-05 20:27:03
【问题描述】:

使用 Phaser 3 时,我无法检测到两个精灵之间的碰撞。我一直在查看文档和几个示例,大部分都已从 Phaser 2 中过时,并且由于某种原因它无法正常工作。

我要做的是一组 ma​​pTiles 和一个 player 角色。现在,我有地板都被传递给对撞机,只是为了测试,没有任何事情发生。

正如您在下面的代码中看到的,我确实有一个与 this.enemies 数组一起使用的碰撞器,所以我不确定为什么它不能与 this.mapTiles 一起使用。此外,在检查我的 ma​​pTiles 的类型时,它们都被标记为 Sprite,而我的 enemies 显然被标记为 ArcadeSprite,会不会是这个问题?

地牢.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
  }
}

编辑

我决定减少一些代码,并给出一个 3 行的小例子来说明什么不起作用。

这是一个只有两个精灵,但仍然无法正常工作。这个小例子将放在我的场景 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)

【问题讨论】:

    标签: javascript collision-detection phaser-framework


    【解决方案1】:

    碰撞在你的身上不起作用,因为精灵没有物理实体。

    如您所述,mapTiles 类型为 Sprite,而敌人类型为 ArcadeSprite,这意味着它们具有物理体。

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

    this.add.sprite(...) 使用 GameObject 工厂(Sprites 是 GameObjects),this.physics.add.sprite(...) 使用物理 Arcade 工厂,它创建一个 sprite,并给它一个物理体。

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

    我不知道你的地图生成器代码是什么样的,但我假设它会是一个类似的修复。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多