简体   繁体   中英

Moving an Object on Canvas

Currently im making a HTML5 Canvas Spaceship Game. But i've got a huge Problem: I created a Class for my Spaceship and i want to move it with the Arrow Keys. But for some Reason it won't move.

The Chrome Inspector won't show any errors but the Spaceship still wont move.

I'm not totally sure but could there be a Problem in the Object from the Class?

You can find the Project Data on my Git: https://github.com/nemoxdelight/First_Game/

Also, sorry for my bad English, i'm just a German who needs help ;)

Also here is the Part where i think the Problem could be: (in the main.js)

function o_move_paddle(p_event) {
    if(p_event.keyCode == KEY_RIGHT) {
        held1.rechtsTaste = true;
        p_event.preventDefault();
    }
    if(p_event.keyCode == KEY_LEFT) {
        held1.linksTaste = true;
        p_event.preventDefault();
    }
    if(p_event.keyCode == KEY_UP) {
        held1.hochTaste = true;
        p_event.preventDefault();
    }
    if(p_event.keyCode == KEY_DOWN) {
        held1.runterTaste = true;
        p_event.preventDefault();
    }
}

And in the held.js where my Heroclass is created and it should move the Object:

Held.prototype.tasteCheck = function() {
    if(this.hochTaste) {
        this.held_y -= this.speed;
    }
    if(this.rechtsTaste) {
        this.held_x += this.speed;
    }
    if(this.linksTaste) {
        this.held_x -= this.speed;
    }
    if(this.runterTaste) {
        this.held_y += this.speed;
    }
};

Your problem is that you (re)create your hero inside the main loop of your game. So every time your game gets in the loop it makes a new hero at the begin coordinates. Therefor appearing not to move.

Here is a quick and dirty solution to your problem. Inside your main.js change the 'loop' function so it is this

function loop(){
  clearCanvas();
  level();
  if(!held1)
    held1 = new Held();
  held1.draw();
  feinde_zeichnen();
  // snd.play();
}

You should create your hero elsewhere, before the loop is initiated, and only once so you can be sure it is always the some object.

EDIT:

Before i forget: you should reset the rechtsTaste,linksTaste,hochTaste and runterTaste variables of your held in the 'o_stop_paddle' function or it will keep moving once you let go of the key as well as stop moving all together once you pressed all directions as it will try to move in all directions, which equates to no movement at all.

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