代码改变世界

processing ball gravity simulation

  youxin  阅读(356)  评论(0编辑  收藏  举报

模拟方案1:

复制代码
void setup() {
  size(500, 500);
  smooth();
}
 
float yPos=25;
float g=.15;
float acceleration=0;
 
void draw() {
  background(0);
  makeball();
  yPos += acceleration;
  //ball drop or bounce back
  acceleration += g;
  //accelerate speed add g
  //when bounce back, -acceleration+g = slower speed
  if (yPos>height-25) {
    acceleration=-acceleration/1.15;
    //when hit bottom, bounce back, but drop down at lower height
    //Thanks to Mauricio
  }
}
 
void makeball() {
  ellipse(width/2, yPos, 50, 50);
  fill(255);
}
复制代码

 

方案2:

复制代码
// Learning Processing
// Daniel Shiffman
// http://www.learningprocessing.com

// Example 5-9: Simple Gravity

float x = 100;   // x location of square
float y = 0;     // y location of square

float speed = 0;   // speed of square

// A new variable, for gravity (i.e. acceleration).   
// We use a relatively small number (0.1) because this accelerations accumulates over time, increasing the speed.   
// Try changing this number to 2.0 and see what happens.
float gravity = 0.1;  

void setup() {
  size(200,200);

}

void draw() {
  background(255);

  // Display the square
  fill(175);
  stroke(0);
  rectMode(CENTER);
  rect(x,y,10,10);
  
  // Add speed to location.
  y = y + speed;
  
  // Add gravity to speed.
  speed = speed + gravity;
  
  // If square reaches the bottom
  // Reverse speed
  if (y > height) {
    // Multiplying by -0.95 instead of -1 slows the square down each time it bounces (by decreasing speed).   让speed乘以-0.95《1,使高度小于最开始的高度。
    // This is known as a "dampening" effect and is a more realistic simulation of the real world (without it, a ball would bounce forever).
    speed = speed * -0.95;  
  }
}
复制代码

2种方法都差不多,只不过参数不同而已。

编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
历史上的今天:
2012-04-02 'GetDc' : undeclared identifier
点击右上角即可分享
微信分享提示