Reputation: 5
OK I'm new to coding and tried to make a little pong clone. somehow this object disappears when it hits the bottom of the canvas element.
Here is my code:
var padle = {
x: 0,
y: 150,
w: 20,
h: 50,
// Add vx and vy properties here:
vx: 0,
vy: 100,
ax: 0,
ay: 0,
color: "#FAFAFA",
draw: function() {
ctx.beginPath();
ctx.fillRect(this.x, this.y, this.w, this.h );
ctx.fillStyle = this.color;
ctx.fill();
},
update: function() {
// Update the particle's position
this.vx += this.ax / FPS;
this.vy += this.ay / FPS;
this.x += this.vx / FPS;
this.y += this.vy / FPS;
if ( this.x < 0 ) {
this.x = 0;
this.vx = -this.vx;
}
if ( this.x > canvas.width ) {
this.x = canvas.width;
this.vx = -this.vx;
}
if (this.y < 0 ) {
this.y = 0;
this.vy = -this.vy;
}
if ( (this.y + this.h)> canvas.height ) {
this.y = canvas.height;
this.vy = -this.vy;
}
}
};`
what's wrong? I really don't get it.
Upvotes: 0
Views: 189
Reputation: 1561
Your statement
if ( (this.y + this.h)> canvas.height ) {
this.y = canvas.height;
this.vy = -this.vy;
}
sets this.y
to canvas.height
, when it should REALLY set it to canvas.height - this.h
. What's happening is that you're telling the item "If your bottom edge is below the canvas, then set your top edge to be exactly at the bottom of the canvas" and causes this code to evaluate every single time in your loop, which is why it seems to "disappear". It's stuck below the bottom of the canvas.
Upvotes: 2