Ray Joe
Ray Joe

Reputation: 202

Collide not working properly

I am trying to learn developing HTML5 games with Phaser.js by using some of their examples, but I am running with a bit of troubles with colliding objects. It works well when the 'dude' sprite collides with the platform 'ground', but when I added the pipe image, the 'dude' sprite never collides with it. Any suggestions?

Entire code:

<!DOCTYPE html>
<html>
<head>
    <title>scene2</title>
</head>
<body>


<script type="text/javascript" src="./js/phaser.js"></script>
<script type="text/javascript">
var game = new Phaser.Game(800, 600, Phaser.AUTO, '', { preload: preload, create: create, update: update });

    function preload(){
     game.load.image('sky', './imgs/sky.png');
     game.load.image('ground', './imgs/platform2.png');
     game.load.image('pipe', './imgs/pipe.png');
     game.load.spritesheet('dude', './imgs/dude.png', 32, 48);
    }

    var 
    sky,
    player,
    platforms,
    pipe;

    function create(){

    game.physics.startSystem(Phaser.Physics.ARCADE);
    sky = game.add.image(0, 0, 'sky');
    sky.scale.setTo(2, 2);

    platforms = game.add.group();
    platforms.enableBody = true;
    var ground = platforms.create(0, game.world.height - 64, 'ground');
    ground.scale.setTo(500, 2);
    ground.body.immovable = true;

    pipe = game.add.sprite(32, -150, 'pipe');
    game.physics.arcade.enable(pipe);

    player = game.add.sprite(32, game.world.height - 150, 'dude');
    game.physics.arcade.enable(player);
    player.body.bounce.y = 0.2;
    player.body.gravity.y = 300;
    player.body.collideWorldBounds = true;

    player.animations.add('left', [0, 1, 2, 3], 10, true);
    player.animations.add('right', [5, 6, 7, 8], 10, true);

    }

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

        var cursors = game.input.keyboard.createCursorKeys();
        player.body.velocity.x = 0;

        if (cursors.left.isDown)
        {
        //  Move to the left
        player.body.velocity.x = -150;

        player.animations.play('left');
        }
        else if (cursors.right.isDown)
        {
        //  Move to the right
        player.body.velocity.x = 150;

        player.animations.play('right');
        }
        else
        {
        //  Stand still
        player.animations.stop();

        player.frame = 4;
        }

        //  Allow the player to jump if they are touching the ground.
        if (cursors.up.isDown && player.body.touching.down)
        {
        player.body.velocity.y = -350;
        }
    }
</script>
</body>
</html>

Upvotes: 0

Views: 969

Answers (1)

Shohanur Rahaman
Shohanur Rahaman

Reputation: 387

add game.physics.enable(platforms, Phaser.Physics.ARCADE); before

platforms = game.add.group();

This phaser example - sprite-vs-group may be helpful.

Upvotes: 4

Related Questions