书名:代码本色:用编程模拟自然系统
作者:Daniel Shiffman
译者:周晗彬
ISBN:978-7-115-36947-5
目录
图3-43.3 三角函数
1、三角函数
- soh:正弦(sin) = 对边 / 斜边
- cah :余弦(cos) = 邻边 / 斜边
- toa :正切(tan) = 对边 / 邻边
2、炮弹发射
模拟物体被大炮射出的场景,在这个过程中,物体受两个力的作用,即
发射力(只有一次)和重力(一直作用在物体上)
float angle = -PI/4;
PVector position = new PVector(50, 300);
boolean shot = false;
CannonBall ball;
void setup() {
size(640, 360);
ball = new CannonBall(position.x, position.y);
}
void draw() {
background(255);
pushMatrix();
translate(position.x, position.y);
rotate(angle);
rect(0, -5, 50, 10);
popMatrix();
if (shot) {
PVector gravity = new PVector(0, 0.2);
ball.applyForce(gravity);
ball.update();
}
ball.display();
if (ball.position.y > height) {
ball = new CannonBall(position.x, position.y);
shot = false;
}
}
void keyPressed() {
if (key == CODED && keyCode == RIGHT) {
angle += 0.1;
}
else if (key == CODED && keyCode == LEFT) {
angle -= 0.1;
}
else if (key == ' ') {
shot = true;
PVector force = PVector.fromAngle(angle);
force.mult(10);
ball.applyForce(force);
}
}
CannonBall.pde
class CannonBall {
// All of our regular motion stuff
PVector position;
PVector velocity;
PVector acceleration;
// Size
float r = 8;
float topspeed = 10;
CannonBall(float x, float y) {
position = new PVector(x,y);
velocity = new PVector();
acceleration = new PVector();
}
// Standard Euler integration
void update() {
velocity.add(acceleration);
velocity.limit(topspeed);
position.add(velocity);
acceleration.mult(0);
}
void applyForce(PVector force) {
acceleration.add(force);
}
void display() {
stroke(0);
strokeWeight(2);
pushMatrix();
translate(position.x,position.y);
fill(0,200,0);
ellipse(0,0,r*2,r*2);
popMatrix();
}
}
3、运行结果
左、右箭头,旋转炮筒角度;
按空格发射炮弹,加力;
网友评论