Hit detection algorithm doesn't work, unsure why not. (Javascript / Processing.js)

I am new to game programming (and programming in general). I've previously made a clone of Flappy Bird and several others and I used the hit detection algorithm provided by the Mozilla Developer Network here .

Now I'm trying to recreate Pong, but for some reason it doesn't work in my current code and I have absolutely no idea why not. I want the ball to hit the "paddle" and then come back as it appeared, but right now he's ghosting through the paddle.

I'm using the Processing.js library, but it should be obvious to anyone (familiar or not) what my code is trying to achieve. The draw () function is often called by processing .js.

The code in action (but not working as expected) can be found 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();

};

      

+3


source to share


2 answers


In the method, drawPlayer

you draw the player at a point (10, mouseY)

, but you never update the y

player property . It always stays at 0. I would recommend that you add a method update

that changes the player's state and changes the draw method to display the player exclusively in his state. Something like



Player.prototype.updatePlayer = function() {
    this.y = mouseY;
};

Player.prototype.drawPlayer = function() {
    rect(this.x , this.y, this.width, this.height);
};

draw = function() {
    // ... 
    player.updatePlayer();
    player.drawPlayer();
    ball.drawBall();
    // ...
};

      

+2


source


In drawPlayer

you can add the linethis.y = mouseY

Player.prototype.drawPlayer = function() {
    rect(10,mouseY, this.width, this.height);
    this.y = mouseY;        
};

      



Fiddle: http://jsfiddle.net/z0acb8gy/

+1


source







All Articles