Tilemap Collisions don't work in Phaser

こ雲淡風輕ζ 提交于 2019-12-11 04:16:49

问题


I'm a complete newbie in Phaser, and I've been having this problem for the last couple of days. Basically, I want my player to collide with the CollisionsLayer in my .json tilemap, but it doesn't work and the player goes right through. I have tried multiple versions of Phaser and none of them seem to work. Here's my code:

<!DOCTYPE html>
<html>
<head>
    <title>RPG Game</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/phaser/2.3.0/phaser.min.js"></script>
</head>
<body>
<script>
var game = new Phaser.Game(1000,600,Phaser.AUTO,'',{preload: preload, create: create, update: update});

function preload() {
    game.load.tilemap('level', 'assets/level1.json', null, Phaser.Tilemap.TILED_JSON);
    game.load.image('tiles', 'assets/tiles.png');
    game.load.image('player', 'assets/star.png');
}

var map;
var backgroundLayer;
var collisionLayer;
var player;
var cursors;

function create() {
    game.physics.startSystem(Phaser.Physics.ARCADE);

    map = game.add.tilemap('level');
    map.addTilesetImage('tiles');

    backgroundLayer = map.createLayer("BackgroundLayer");
    collisionLayer = map.createLayer("CollisionLayer");
    map.setCollisionBetween(1,80);
    backgroundLayer.resizeWorld();

    player = game.add.sprite(200,200,'player');

    game.physics.enable(player);

    game.camera.follow(player);

    cursors = game.input.keyboard.createCursorKeys();

}

function update() {
    game.physics.arcade.collide(player, collisionLayer);

    player.body.velocity.x = 0;
    player.body.velocity.y = 0;

    if (cursors.right.isDown) {
        player.body.velocity.x = 200;
    }
    else if (cursors.left.isDown) {
        player.body.velocity.x = -200;
    }
    else if (cursors.up.isDown) {
        player.body.velocity.y = -200;
    }
    else if (cursors.down.isDown) {
        player.body.velocity.y = 200;
    }
}
</script>
</body>
</html>

The tilemap does load and I am able to move but I just don't collide with any tiles on the collision layer. Thanks in advance.


回答1:


You need to add this code after creating the collisionLayer object in the create() function:

game.add.existing(collisionLayer);

Or this code in the map.createLayer constructor:

this.game.add.existing(this);

But depends on your code. The thing is that you have to explicitly tell Phaser that the object is being added to the game.



来源:https://stackoverflow.com/questions/30154858/tilemap-collisions-dont-work-in-phaser

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!