Reputation: 3731
I'm making a little canvas game and adding in some power ups that the player can collect. Here's what I use to make them appear:
thePowerUps.forEach ( function(t)
{
c.beginPath();
c.save();
c.translate(t.x,t.y);
c.fillStyle = t.fill;
c.moveTo(t.x - 15, t.y - 15);
c.lineTo(t.x + 15, t.y - 15);
c.lineTo(t.x + 15, t.y + 15);
c.lineTo(t.x - 15, t.y + 15);
c.lineTo(t.x - 15, t.y - 15);
c.fill();
c.restore();
c.closePath();
});
So I'm cycling through the power ups array drawing each one. In my test case t.x and t.y are both 200. But this code draws the power up at the location 400, 400. I console logged the power ups array, which returned 200 for x and y. If I move the player character over the coordinates 200,200, the power up, drawn at 400,400 disappears and the code for the power up executes.
So for all functional purposes, it's in the right place. It just doesn't appear there. Yet the player, the bad guy and the bullets are all in the correct coordinates.
I've tried doing this;
c.beginPath();
c.save();
c.translate(150,150);
c.fillStyle = 'orange';
c.moveTo(150 - 15, 150 - 15);
c.lineTo(150 + 15, 150 - 15);
c.lineTo(150 + 15, 150 + 15);
c.lineTo(150 - 15, 150 + 15);
c.lineTo(150 - 15, 150 - 15);
c.fill();
c.restore();
c.closePath();
A "static" box without looking up the values in the array. This too draws in the wrong location (300,300 in this case). I've tried putting this at different locations in the game loop (including before and after the code for the parts that are drawn correctly). No effect.
Here's the code for the zombie bad guys, which are drawing in the right place:
c.beginPath();
c.save();
c.translate(i.x,i.y);
zomAngle = getZomAngle(i.x, i.y);
if (Player1.x - i.x < 0) {
c.rotate(zomAngle);
}
else {
c.rotate(zomAngle);
c.scale(-1,1);
}
c.translate(-i.x,-i.y);
c.fillStyle = i.fill;
c.moveTo(i.x - 18, i.y);
c.lineTo(i.x + 18, i.y + 15);
c.lineTo(i.x + 18, i.y - 15);
c.lineTo(i.x - 18, i.y);
c.fill();
c.restore();
c.closePath();
As you can see it's basically the same thing, except the bad guys have a rotate to keep them facing the player. I tried adding that to the power up, but it had no effect -- they were still triggered by walking over 200,200 no matter where they box was actually being drawn.
Any ideas?
Upvotes: 0
Views: 83
Reputation: 276
If you use translate(x, y) then all your following drawing instructions will be drawn relative from that position. You are essentially offsetting your drawing instructions twice now. Instead, you should do something like this:
thePowerUps.forEach ( function(t)
{
c.beginPath();
c.save();
c.translate(t.x,t.y);
c.fillStyle = t.fill;
c.moveTo(-15, -15);
c.lineTo(15, -15);
c.lineTo(15, 15);
c.lineTo(-15, 15);
c.lineTo(-15, -15);
c.fill();
c.restore();
c.closePath();
});
Upvotes: 1