如何在Processing中實現彈跳球動畫?

彈跳球在Processing中是一個很是經典的動畫效果,就是一個球在兩堵牆中間不停地碰撞,能夠在Processing中使用如下代碼實現:函數

float circleX;
float xspeed = 10;

void setup(){
  size(640, 360);
  circleX = 0;
}

void draw(){
  background(50);
  fill(150);
  stroke(255);
  ellipse(circleX, height/2, 20, 20);
  circleX = circleX + xspeed;
  
  if(circleX > width || circleX < 0){
     xspeed = xspeed * -1;
  }
}

代碼的關鍵是在xspeed這個變量上,由於在draw函數中,代碼一直循環執行,因此小球的橫座標circleX是隨着xspeed變化的。當circleX的位置大於width或者小於0的時候,xspeed經過* -1變成反向。
2_1.gif動畫

若是咱們想模擬小球撞到牆後,能量損失的過程,能夠把xspeed = speed * -1 變爲 xspeed = xspeed * -0.9 spa

2_2.gif

可是發現小球到達最右邊的時候,像是被卡住了似的,咱們能夠分析小球到達右邊時候circleXxspeed的變化。code

若是小球的circleX 等於370,那麼xspeed變爲-9,因此下個循環circleX變爲361,仍是大於360,這時候xspeed變爲8.1,下個循環circleX變爲369.1,這時候xspeed變爲-7.29。咱們把它們可能的值列在下面:blog

circleX = 370, xspeed = -9
circleX = 361, xspeed = 8.1
circleX = 369.1, xspeed = -7.29
circleX = 361.81, xspeed = 6.561
circleX = 368.371, xspeed = -5.9049
circleX = 362.461, xspeed = 5.31414
...

從上面值能夠看出,小球一直在360-370這個區間震盪,沒法返回。能夠改爲下面的代碼,限制小球不能超過整個畫布的大小,就能夠讓小球正常返回,否則就會在邊緣震盪:ip

if(circleX > width){
    xspeed = xspeed * -0.9;
    circleX = width;
  }
  
  if(circleX < 0){
    xspeed = xspeed * -0.9;
    circleX = 0;
  }

2_3.gif

相關文章
相關標籤/搜索