[英]How to accelerate the ball in pong in js
我想在比賽中加快球速。 這是我的乒乓球的代碼:
Ball.prototype = {
Draw : function () {
this.context.fillStyle = this.color;
this.context.fillRect( this.posX, this.posY, this.diameter, this.diameter );
},
GetBallDirection : function () {
if ( this.pitchX > 0 ) {
return "right";
} else if ( this.pitchX < 0 ) {
return "left";
}
return "none";
},
Update : function () {
this.posX += this.pitchX;
if ( this.posX > this.courtWidth )
return 1;
if ( this.posX + this.diameter <= 0 )
return 2
this.posY += this.pitchY;
if ( this.posY > this.courtHeight || this.posY <= 0 ) {
this.pitchY = - this.pitchY;
}
return 0;
},
Center : function () {
this.posX = this.courtWidth / 2 - this.diameter / 2;
this.posY = this.courtHeight / 2 - this.diameter / 2;
}
}
此刻,您可以使用以下代碼更新球的位置:
Update : function () {
this.posX += this.pitchX;
//(...)
this.posY += this.pitchY;
//(...)
},
從字面上看:“使用this.pitchX在x軸上移動球,使用this.pitchY在y軸上移動球”
要更改球的速度,最好的辦法是創建一個“速度”屬性,然后使用它。 像這樣:
this.speed = 1; // Speed = normal (100%)
現在,我們可以調整Update
功能:
Update : function () {
this.posX += (this.pitchX * this.speed);
//(...)
this.posY += (this.pitchY * this.speed);
//(...)
},
現在,如果您想加快或降低球速,只需將this.speed
更改為其他值即可。
this.speed = 0.5; //Ball will go half as fast
this.speed = 2; //Ball will go twice as fast.
this.speed += 0.01; //Ball will speed up with 1% each update.
為了加快球的速度,您可以在update
功能中對此進行更改:
this.posY += (this.pitchY*2);
this.posX += (this.pitchX*2);
因此,球將快兩倍。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.