试图在JS中创建一个Pong克隆,但是paddles不会与球交互

时间:2017-05-17 15:12:13

标签: javascript pong

我正在尝试按照指南在Javascript中创建我自己的Pong克隆。到目前为止,我已经设法绘制画布,创建一个球和桨,我试图看看球是否会与桨相互作用。问题是它不会与它们互动。我不确定我是否遗漏了代码方面的错误,或者我是否完全忽略了一些巨大的错误。 StackOverflow上的所有问题都是使用不同的编码语言,或者我无法理解它们。

我很感激能得到任何帮助!

var animate = window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
function(callback) { window.setTimeout(callback, 1000/60) }; 


var canvas = document.createElement("canvas");
var width = 900;
var height = 600;
canvas.width = width;
canvas.height = height;
var context = canvas.getContext("2d");

window.onload = function() {
 document.body.appendChild(canvas);
 animate(step);
};

var step = function() {
 update();
 render();
 animate(step);
};

var update = function() {
 ball.update(player1.paddle, player2.paddle);
};

Ball.prototype.update = function(spelare1, spelare2) {
 this.x += this.x_speed;
 this.y += this.y_speed;
 var top_x = this.x - 5;
 var top_y = this.y - 5;
 var bottom_x = this.x + 5;
 var bottom_y = this.y + 5;

if(this.y - 5 < 0 ) { 
 this.y = 5;
 this.y_speed = -this.y_speed;
} else if(this.y + 5 > 900) { 
 this.y = 450;
 this.y_speed = -this.y_speed;
}

if(this.x < 0 || this.x > 900) { 
 this.x_speed = 3;
 this.y_speed = 0;
 this.x = 450;
 this.y = 300;
}


if(top_x > 900){

if(top_y > (player2.y + player2.height) && bottom_y < player2.y && top_x > 
  (player2.x + player2.width) && bottom_x < player2.x) {

  this.x_speed = -3;
  this.y_speed += (player2.y_speed / 2);
  this.y += this.y_speed;
}
} else {
if(top_y < (player1.y + player1.height) && bottom_y < player1.y && top_x < 
(player1.x + player1.width) && bottom_x < player1.x) {
  // bollen nuddar player1
  this.x_speed = 3;
  this.y_speed += (player1.y_speed / 2);
  this.y += this.y_speed;
}
}
}; 

var render = function() {
 context.fillStyle = "black";
 context.fillRect(0, 0, width, height);
 player1.render();
 player2.render();
 ball.render();
}; 

function Paddle(x, y, width, height) {
 this.x = x;
 this.y = y;
 this.width = width;
 this.height = height;
 this.x_speed = 0;
 this.y_speed = 0;
};

Paddle.prototype.render = function() {
 context.fillStyle = "white";
 context.fillRect(this.x, this.y, this.width, this.height);
};

function spelare1 () {
 this.Paddle = new Paddle(10, 275, 10, 75);
};
function spelare2 () {
 this.Paddle = new Paddle(880, 275, 10, 75);
}; 

spelare1.prototype.render = function () {
 this.Paddle.render();
}; 

spelare2.prototype.render = function () {
 this.Paddle.render();
}; 

function Ball(x, y) {
 this.x = x;
 this.y = y;
 this.x_speed = 0;
 this.y_speed = 3;
 this.radius = 4;
};

Ball.prototype.render = function() {
 context.beginPath();
 context.arc(this.x, this.y, this.radius, 2 * Math.PI, false);
 context.fillStyle = "white";
 context.fill();
}; 

var player1 = new spelare1(); 
var player2 = new spelare2(); 
var ball = new Ball(450, 300); 

0 个答案:

没有答案