编程语言
首页 > 编程语言> > 命中检测算法不起作用,不确定为什么不起作用. (Javascript / Processing.js)

命中检测算法不起作用,不确定为什么不起作用. (Javascript / Processing.js)

作者:互联网

我是游戏编程(和一般编程)的新手.我以前制作过“ Flappy Bird”克隆和其他一些克隆,并且使用了Mozilla开发人员网络here提供的点击检测算法.

我现在正在尝试重新创建“ Pong”,但是由于任何原因,它在我的当前代码中均不起作用,因此我完全不知道为什么不这样做.我希望球打到“桨”上,然后再回去,但是现在它在桨上出现了鬼影.

我正在使用Processing.js库,但对于任何人(无论是否熟悉),我的代码都试图实现. draw()函数经常被processing.js调用.

运行中的代码(但未按预期运行)可以找到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();

};

解决方法:

在drawPlayer方法中,您在(10,mouseY)点绘制了播放器,但从未更新播放器的y属性.它始终保持等于0.我建议您添加更新方法,该方法将更改播放器的状态并更改绘制方法以仅在其状态下呈现播放器.就像是

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();
    // ...
};

标签:processing-js,javascript
来源: https://codeday.me/bug/20191120/2043235.html