Jump to content

How Do I Handle Collision With a Layer?


EpicToast
 Share

Recommended Posts

Hello all,

I am currently trying to make a simple platformer, but am having trouble detecting collision with a tile layer.  

After looking through many of the other forum posts here about this problem, none of the fixes seem to work for me.  'World 1' layer is the background and 'Collision' is the layer that contains the platforms.  

To my understanding, I should just be able to use map.setCollisionBetween() on the tiles that I want to use as the ground, which I think I did correctly.  I also made sure to enable physics for the player and the collision layer.  For some reason, though when I console.log(game.physics.arcade.collide(player, col)), it always returns false.  When I run console.log(player.body.blocked), it only returns true when the player is on the window boundary (because of collideWorldBounds=true).

Can anyone see what I'm doing wrong?

var game = new Phaser.Game(800, 480, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update });

function preload() {

    game.load.tilemap('bgmap', 'assets/tilemaps/maps/superMarioBG.json', null, Phaser.Tilemap.TILED_JSON);
    game.load.image('bgtiles', 'assets/tilemaps/tiles/super_mario.png');

    game.load.image('player', 'assets/sprites/georgeRight.png');
}

var map;
var bg;
var col;
var player;
var cursors;
var jumpButton;

function create() {

    game.physics.startSystem(Phaser.Physics.ARCADE);
    
    game.stage.backgroundColor = '#787878';

    map = game.add.tilemap('bgmap');
        
    map.addTilesetImage('SuperMarioBros', 'bgtiles');
    
    bg = map.createLayer('World1');
    bg.scale.set(2);
    bg.resizeWorld();
    col = map.createLayer('Collision');
    col.scale.set(2);
    game.physics.arcade.enable(col);
    
    map.setCollisionBetween(1,40,true,col);
    col.resizeWorld();

    player = game.add.sprite(0,game.world.height - 150,'player');
    player.scale.set(1.5) ;
    player.anchor.setTo(.5,.5);
    
    cursors = game.input.keyboard.createCursorKeys();
    jumpButton = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);


    game.physics.arcade.enable(player);
    
    player.body.bounce.y = 0.2;
    player.body.gravity.y = 500;
    player.body.collideWorldBounds = true;
    
}
    //
function update() {
    
    game.physics.arcade.collide(player, col);
    player.body.velocity.x=0;
    game.camera.follow(player);
    if (cursors.left.isDown)
    {
        player.body.velocity.x -= 500;
    }
    else if (cursors.right.isDown)
    {
        player.body.velocity.x += 500;
    }
    if (jumpButton.isDown && player.body.onFloor()) {
        player.body.velocity.y = -550;
    }
console.log(player.body.blocked);

    }
    
    function render() {
        
    }
};

 

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...