Ultimate Guide to the Processing Language Part II: Building a Simple Gameを参考に、プログラムを書いております。
しかしながら、frictionを導入し実行したところ、ボールの速さは0に近づいていくのですが、ある一定のところでボールの速さの絶対値の減少はストップし、ボールが床で止まりません。
以下のようなコードです。どこが問題なのでしょうか。
int gameScreen = 0;
int ballX, ballY;
int ballSize = 20;
int ballColor = color(0);
float gravity = 1;
float ballSpeedVert = 0;
float airfriction = 0.0001;
float friction = 0.1;
void setup() {
size(500,500);
ballX = width/4;
ballY = height/5;
}
void draw() {
//Display the contents of the current scree
if (gameScreen == 0){
initScreen();
}else if (gameScreen == 1){
gameScreen();
}else if (gameScreen == 2){
gameOverScreen();
}
}
// SCREEN CONTENTS
void initScreen(){
background(0);
textAlign(CENTER);
text("Click to start.", height/2, width/2);
}
void gameScreen(){
background(255);
drawBall();
applyGravity();
keepInScreen();
}
void gameOverScreen(){
}
// INPUTS
public void mousePressed() {
//If we are on the initial screen when clicked, start the game
if (gameScreen == 0) {
startGame();
}
}
//OTHER FUNCTION
void startGame(){
gameScreen = 1;
}
void drawBall(){
fill(ballColor);
ellipse(ballX, ballY,ballSize,ballSize);
}
void applyGravity() {
ballSpeedVert += gravity;
ballY += ballSpeedVert;
// ballSpeedVert -= (ballSpeedVert * airfriction);
}
void makeBounceBottom(int surface){
ballY = surface - (ballSize/2);
ballSpeedVert *= -1;
ballSpeedVert -= (ballSpeedVert * friction); <-床にあたったときの摩擦による速度の変化
}
void makeBounceTop(int surface){
ballY = surface + (ballSize/2);
ballSpeedVert *= -1;
ballSpeedVert -= (ballSpeedVert * friction);
}
void keepInScreen(){
// ball hits floor
if(ballY + (ballSize/2) > height){
makeBounceBottom(height);
}
// ball hits ceiling
if(ballY - (ballSize/2) < 0){
makeBounceTop(0);
}
}