我是编程游戏(和一般编程)的新手。我以前制作了一个“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();
};
答案 0 :(得分:2)
在drawPlayer
方法中,您在(10, mouseY)
点中绘制了玩家,但从不更新玩家的y
属性。它始终保持等于0.我建议你添加update
方法,这将改变玩家的状态,并改变绘制方法,使玩家完全呈现其状态。像
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();
// ...
};
答案 1 :(得分:1)
在drawPlayer
中,您可以添加第this.y = mouseY
行
Player.prototype.drawPlayer = function() {
rect(10,mouseY, this.width, this.height);
this.y = mouseY;
};