Search code examples
javascriptimagereversecreatejs

Reverse image on keydown - Javascript


What I am trying to implement here is that I have a character on my screen and I can move it around to the left, right, up and down with a press on my arrow keys.

What I want to do is when I click to the left is that the image will reverse and when I click to the right and it should reverse back, with this the character is always facing the way it walks.

My code looks like this where I define the original image and the reversed one:

Game.Hero = function (myX, myY){
var my = new createjs.Bitmap("img/hero.png");
my.reverseHero = function (){
    my.image.src = "img/hero-1.png";
};

Then I have a code snippet here that shows how I am trying to work this thing out:

my.moveBy = function(dirX, dirY){
    var testX = my.posX + dirX;
    var testY = my.posY + dirY;
    if (testX < 0 || testY < 0 || testX > 21 || testY > 8){
        return;
    }
    if (dirX === -1){
       my.reverseHero();

    } else if (dirX === 1) {
        Game.stage.addChild(Game.hero);                
    }

My problem at this moment, is that when I walk to the left, the image will actually reverse, but when I try to go to the right again, the image will not reverse.

So the code is actually only running the first if statement and just keeps hanging on there.

Do you have any suggestions what could be wrong ?


Solution

  • Aren't you supposed to reset the image after you set it? This means setting a second function to return the hero to his original image. Because now it just sets your character to the other image when that action is called, but that keeps that image set, even when that action isn't called anymore.

    Game.Hero = function (myX, myY){
    var my = new createjs.Bitmap("img/hero.png");
    my.reverseHero = function (){
        my.image.src = "img/hero-1.png";
    };
    my.returnHero = function(){
        my.image.src = "img/hero.png";
    };
    

    Then, in the else if statement, call that function

    my.moveBy = function(dirX, dirY){
        var testX = my.posX + dirX;
        var testY = my.posY + dirY;
        if (testX < 0 || testY < 0 || testX > 21 || testY > 8){
            return;
        }
        if (dirX === -1){
           my.reverseHero();
        } else if (dirX === 1) {
            Game.stage.addChild(Game.hero);                
            my.returnHero();
        }
    

    Does this make sense to you, or should I clarify some more?