Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hit detection algorithm not working, unsure why not. (Javascript/Processing.js)

I'm new to programming games (and programming in general). I have previously made a "Flappy Bird" clone and a few others and I used the hit detection algorithm as provided by the Mozilla Developer Network here.

I am now trying to recreate "Pong" but, for whatever reason, its not working in my current code and I'm completely clueless as to why not. I want the ball to hit the "paddle" and then go back the way it came, but right now it ghosts through the paddle.

I'm using the Processing.js library but it should be apparent to anyone (familiar with it or not) what my code is trying to achieve. The draw() function gets called frequently 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();

};
like image 660
swhizzle Avatar asked Apr 20 '26 13:04

swhizzle


1 Answers

In the drawPlayer method you draw player in the (10, mouseY) point, but never update y property of player. It always remains equal to 0. I would recommend you to add update method, which will change player's state and change draw method to render player purely on its 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();
    // ...
};
like image 182
Eugene Avatar answered Apr 22 '26 03:04

Eugene



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!