繁体   English   中英

Phaser3:检测精灵碰撞

[英]Phaser3: Detecting sprite collision

使用Phaser 3,我无法检测两个精灵之间的碰撞。 我一直在上下文档和几个例子,大多数是从Phaser 2过时的,并且由于某种原因它只是不起作用。

我要去的是一系列mapTiles和一个玩家角色。 现在,我将墙壁地板都传递到对撞机只是为了测试目的而没有任何事情发生。

正如你在下面的代码中看到的,我确实有一个使用this.enemies数组的对撞机,所以我不确定为什么它不能使用this.mapTiles 此外,在检查我的mapTiles的类型时,它们每个都被标记为Sprite ,我的敌人显然被标记为ArcadeSprite ,这可能是问题吗?

在此输入图像描述

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
  }
}

编辑

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

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

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)

碰撞不起作用,因为精灵没有物理体。

如你所知,mapTiles是Sprite类型,其中敌人是ArcadeSprite意味着他们有一个物理体。

创建它们的不同之处在于工厂使用。

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

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

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

暂无
暂无

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

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