Owl
Owl

Reputation: 689

Speed up sprite on click on phaser

I have a game with a background and a car sprite.

The car is driving now from right to left. I'm trying to make it so that when the player clicks the car, the car speeds up and continue it's way faster.

My code so far:

var game = new Phaser.Game(800, 500, Phaser.AUTO, '', { preload: preload, create: create, update: update });
var text;
var counter = 0;

function preload() {
    game.load.image('background', 'images/backgrounds/bg_g1a.png');
    game.load.image('car', 'images/items/car.png');
}

function create() {
    // enable the Arcade Physics system
    game.physics.startSystem(Phaser.Physics.ARCADE);
    // Game background
    game.add.sprite(0, 0, 'background');
    //add car
    var sprite = game.add.sprite(700, 300, 'car');
    game.physics.arcade.enable(sprite);
    // add movement from right to left
    var demoTween = game.add.tween(sprite).to({x:-200,y:300},2000);
    // start again when out of the game
    demoTween.onComplete.add(function(){
        sprite.x = 700; sprite.y = 300;
        demoTween.start();
    });
    demoTween.start(); 
    //enable input on car
    sprite.inputEnabled = true;
    //counter
    text = game.add.text(250, 16, '', { fill: '#ffffff' });
    //start listener function on input
    sprite.events.onInputDown.add(listener, this); 
}

function update() {
}
// car has been clicked
function listener (sprite) {
    counter++;
    text.text = "You clicked " + counter + " times!";
    sprite.body.acceleration = -2000; 
}

I have tried on the last line:

sprite.body.acceleration = -2000; 

I have tried different methods from velocity to change tween Data, but none of them work. The counter counts, but the car keeps moving like before. What am I doing wrong?

Upvotes: 0

Views: 1060

Answers (1)

Owl
Owl

Reputation: 689

Ok I got it.

The problem is the different methods of moving the object. It can be done via tween, via moving the object by itself or via physics.

But you cannot mix them! This was causing the problem. So in my case, I now move the sprite with moveToXY and then accelerate. Like this:

game.physics.arcade.moveToXY(policecar, 100, streetHeight);

Then when clicked on, the listener function fires this:

sprite.body.acceleration.x = -1000;

Works well!

Upvotes: 1

Related Questions