rezoner / CanvasQuery

Canvas for 2d gamedevelopers. Out of box canvas, keyboard, mouse, events.
http://canvasquery.com
586 stars 52 forks source link

copy cat movement issue #17

Closed WaffleGnome closed 10 years ago

WaffleGnome commented 11 years ago

i just started using CanvasQuery so far i like it but im having trouble figuring something out. i have two blocks on my canvas and i want the "player' block to be key controllable, so far i have that part working but then i created an "enemy" and now when the user moves "player" the "enemy" also moves. i plan on having the "enemy" relocate on collision with "player" how can keep the blocks from moving together and where do i have to give "enemy" its own special functions? i checked out the other examples but i couldn't find any examples with more than one object on screen.

WaffleGnome commented 11 years ago
var player = { 
    x: 200, 
    y: 100,
    width: 32, 
    height: 32 
};
var enemy = { 
    x: 10, 
    y: 10,
    width: 32, 
    height: 32 
};
/* create fullscreen canvas */
cq().framework({

    onResize: function(width, height) {

        /* resize canvas with window */
        this.canvas.width = 700;
        this.canvas.height = 600;
    },

  /* in canvasquery you just need to type in keynames!!!! */
  /* enemy moves with player(must fix) */
  onKeyDown: function(key) {
        if(key == "left" ) player.x -= 10;
        if(key == "right") player.x += 10;
        if(key == "up") player.y -= 10; 
        if(key == "down") player.y += 10;},

  /* testing out moving seperate objects */
  /* enmey keeps moving far left when moue enters screen... */
  onMouseMove: function(x, y) { 
        enemy.x = x;
        enemy.y = y;    
    },
    onStep: function(delta) {},
    onRender: function() {  
        /* draw player */       
        this.save()
            .clear("cyan")   
      /* when this is translate is removed the enemy block is centeterd corectly on mouse cursor */
            .translate(player.x, player.y)
            .fillStyle("white")   
            .fillRect( -player.width / 2, -player.height / 2, player.width, player.height)
    .fill()

        .fillStyle("red") 
     .translate(enemy.x, enemy.y)
            .fillRect( -enemy.width / 2, -enemy.height / 2, enemy.width, enemy.height)
    .fill()
        .restore();
    }
}).appendTo("body");Check out this Pen!
rezoner commented 11 years ago

Add another restore() and save() right after the player is drawn

save()
drawPlayer()
restore()

save()
drawEnemy
restore()
WaffleGnome commented 11 years ago

Thanks for the quick response! Wow the solution was so simple that it just flew right over my head >_<