作者 主题: 如何让运动的球停下来  (阅读 3862 次)

big_fat_meal

  • Newbie
  • *
  • 帖子: 33
如何让运动的球停下来
« 于: 六月 21, 2012, 12:31:07 上午 »
raven讲了个球运动的例子,但没说怎么停在地上,所以自己琢磨着写了一段很初级的程序,有点繁琐,不过总算是让球停了下来,小有成果

float xPos;
float yPos;
float increx = 5;
float increy = 5;
float gravity = 0.5;
float friction = 0.02;
void setup() {
  smooth();
  fill(148, 65, 222);
  size(500, 500);
  frameRate(30);
  yPos = height/2;
  xPos = width/3;
}
void draw() {
  background(255);
  ellipse(xPos, yPos, 20, 20);
  xPos+=increx;
  yPos+=increy;
  if (xPos>width-10) {
    xPos = width-10;
    increx = -increx*0.9;
  }
  else if (xPos<10) {
    xPos = 10;
    increx = - increx*0.9;
  } 
  if ( yPos>height-10) {
    yPos=height-10;
    increy = -increy*0.9;
  }
  else if (yPos<10) {
    yPos = 10;
    increy = -increy*0.9;
  }
 
  if (yPos == height-10) {
      if (increx >0){
          increx =increx-friction;
      } 
      if(increx <0){
          increx =increx +friction;
      }
      if (increx*friction == 0)
          increx =0;
    }
 
  increy += gravity;
}

big_fat_meal

  • Newbie
  • *
  • 帖子: 33
Re: 如何让运动的球停下来
« 回复 #1 于: 六月 21, 2012, 03:45:37 下午 »
我错了,球没有真正的停下来,每过10秒钟就会有一次很小的滚动,这个怎么搞的?哪里错了

RavenKwok

  • Sr. Member
  • ****
  • 帖子: 277
  • Artist/ Animator/ Coder/ Cynical Asshole
Re: 如何让运动的球停下来
« 回复 #2 于: 六月 22, 2012, 04:16:44 下午 »
@big_fat_meal

 :)

程序代码
float xPos;
float yPos;
float increx = 5;
float increy = 5;
float gravity = 0.5;
float friction = 0.99;

void setup() {
  smooth();
  fill(148, 65, 222);
  size(500, 500);
  frameRate(30);
  yPos = height/2;
  xPos = width/3;
}
void draw() {
  background(255);
  ellipse(xPos, yPos, 20, 20);

  increy += gravity;
  xPos += increx;
  yPos += increy;

  if (xPos>width-10) {
    xPos = width-10;
    increx = -increx*0.9;
  }
  else if (xPos<10) {
    xPos = 10;
    increx = - increx*0.9;
  }

  if ( yPos>height-10) {
    yPos=height-10;
    increy = -increy*0.9;
  }
  else if (yPos<10) {
    yPos = 10;
    increy = -increy*0.9;
  }

  if (abs(increx)>0.5) {
    if (yPos == height-10) {
      increx *= friction;
    }
  }else{
    increx = 0;
  }
}

big_fat_meal

  • Newbie
  • *
  • 帖子: 33
Re: 如何让运动的球停下来
« 回复 #3 于: 六月 22, 2012, 07:10:15 下午 »
噢,原来那个0.5是让小球突然停止的,没有向0的过程

Tags: