简体   繁体   中英

Phaser3 Rotation Animation

I'm trying to create a simple animation effect of a pendulum swinging back and forth. I'm only using a single image sprite for it, and I've got the code below, but the animation only tilts to a 45 angle then stops completely. What might I be doing wrong?

    var title = new Phaser.Scene("GameTitle");
var pendulum;
var direction;
title.create = function(){
    pendulum = this.add.sprite(200, 0, 'titlePendulum').setOrigin(0.5, 0).setScale(1.8).setRotation(79);
    direction = "left";
};

title.update = function(){
    console.log(pendulum.angle.toFixed(0));
    swing(direction);
    if(pendulum.angle.toFixed(0) == 71){
        swing ("right");
    }
    if(pendulum.angle.toFixed(0) == -76){
        swing("left");
    }
};

function swing(dir){
    if(dir == "left"){
        if(pendulum.angle.toFixed(0) == 71){
            swing("right");
        }else{
            pendulum.angle +=1.5;
        }

    }else{
        if(pendulum.angle.toFixed(0) > -80){
            pendulum.angle -= 1.5;
        }
        if(pendulum.angle.toFixed(0) == -76){
            swing("left");
        }
    }
}

I noticed that you check if the pendulum.angle is larger than or exactly equal to 80 in two separate if statements. However 80 is not divisible by 1.5, and the value of the angle could be .. 76, 77.5, 79, 80.5 .. and the condition pendulum.angle.toFixed(0) == 80 will never be true.

Also, the name of the function parameter is dir but you check for a direction .

I'm pretty sure that is causing the problem. Even if that's not it, it's still better (more elegant and "cleaner") to use if-else when you are checking for a condition that can either be one thing or the other, instead of using two separate if statements.

So change your code to something like this:

function swing(dir) {
    if (dir == "left") { // check parameter, not the direction global var
        if (pendulum.angle.toFixed(0) < 80) {
            pendulum.angle +=1.5;
        } else {
            swing("right");
        }
    } else { // dir == "right"
        if (pendulum.angle.toFixed(0) > -80) {
            pendulum.angle -= 1.5;
        } else {
            swing("left");
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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