I am a beginner in game programming and programming in general. In the past, I have created a clone of "Flappy Bird" and some other games using the hit detection algorithm from the Mozilla Developer Network here.
Currently, I am facing an issue while trying to recreate the classic game "Pong". The ball is supposed to hit the paddle and bounce back, but for some reason, it's passing through the paddle. I am using the Processing.js library and the draw() function is called frequently by processing.js.
You can view the code in action (not working as expected) here
var PADDLE_WIDTH = 10;
var PADDLE_HEIGHT = 75;
var PADDLE_X = 10;
var Player = function(y) {
this.x = PADDLE_X;
this.y = mouseY;
this.score = 0;
this.width = PADDLE_WIDTH;
this.height = PADDLE_HEIGHT;
};
Player.prototype.drawPlayer = function() {
rect(10,mouseY, this.width, this.height);
};
var Ball = function(x,y) {
this.x = x;
this.y = y;
this.speed = 4;
this.width = 10;
this.height = 10;
};
Ball.prototype.drawBall = function() {
rect(this.x, this.y, this.width, this.height);
};
Ball.prototype.onHit = function() {
if(this.y <= 0 || this.y >= height) {
this.speed *= -1;
} else if(this.x <= 0 || this.x >= width){
this.speed *= -1;
// HIT DETECTION UNDERNEATH
} else if (player.x < this.x + this.width &&
player.x + player.width > this.x &&
player.y < this.y + this.height &&
player.height + player.y > this.y){
this.speed *= -1;
}
};
var player = new Player();
var ball = new Ball(width/2, height/2);
draw = function() {
background(0);
fill(250, 250, 250);
ball.x -= ball.speed;
player.drawPlayer();
ball.drawBall();
ball.onHit();
};