我为弹跳球创建了一个脚本,我想尝试添加另一个球以使其更有趣。但是代码似乎不起作用,并且正在尝试添加另一个球。我想使用相同的功能,因为它更紧凑和灵活。
function startGame() {
GameArea.start();
Ball = new CircComp('red' , window.innerWidth/ 2 , window.innerHeight / 2.5 );
Ball.yAngle = 10;
Ball.xAngle = 10;
Ball.radius = 20;
Ball1 = new CircComp('green' , window.innerWidth/ 2 , window.innerHeight / 2.5 );
Ball1.yAngle = -10;
Ball1.xAngle = -10;
Ball1.radius = 20;
}
var GameArea = {
canvas : canvas = document.querySelector("canvas"),
start : function (){
this.canvas.width = window.innerWidth;
this.canvas.height = window.innerHeight;
this.ctx = this.canvas.getContext('2d');
this.interval = setInterval(updateGameArea, 20);
},
clear : function() {
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
}
function CircComp(color, x , y){
this.x = x;
this.y = y;
context = GameArea.ctx;
this.update = function(){
context.beginPath();
context.fillStyle = color;
context.arc(this.x,this.y,this.radius,0,2*Math.PI);
context.fill();
context.stroke();
}
this.updateGameComp = function(){
GameArea.clear();
this.y += this.yAngle;
this.x += this.xAngle;
if(this.x + this.radius > GameArea.canvas.width){
this.xAngle = -1 * this.xAngle;
}
if(this.y + this.radius > GameArea.canvas.height){
this.yAngle = -1 * this.yAngle;;
}
if(this.x - this.radius < 0){
this.xAngle = -1 * this.xAngle;
}
if(this.y - this.radius < 0){
this.yAngle = -1 * this.yAngle;
}
this.update();
}
}
function updateGameArea(){
Ball.updateGameComp();
Ball1.updateGameComp();
}
<html>
<head>
<meta charset='urf-8'>
<style>
canvas{
border: 0px solid black;
}
body{
margin: 0;
overflow: hidden;
}
</style>
</head>
<body onload='startGame()'>
<canvas></canvas>
<script src='Pong.js'></script>
</body>
</html>