前言
在《代碼本色》的第1章 向量 中,主要講到了向量的運算、靜態函數和非靜態函數以及向量在運動中的應用,以下爲第1章的內容目錄:
針對向量在運動中的應用,我展開了自己的習作。
關於習作
學習了《代碼本色》第1章 向量 的內容之後,我想在自己的習作中表現的是鍵鼠與畫面的交互以及更多的畫面表現力。具體實現爲:
- Mover跟隨鼠標位置,加速度指向鼠標位置。
- 鍵盤控制最大速度,A鍵加速,S鍵減速,R鍵重置速度。
- Mover是一個圓形,圓心位置與鼠標位置連線,體現牽引關係。
關於第一點和第二點,可以通過在Mover類中加入鼠標和鍵盤事件實現,第三點可以通過line()函數實現,豐富表現力。
通過向量的使用和麪向對象編程思想,實現了鍵鼠和畫面中Mover的交互,牽引線體現了更多的畫面表現力,自己也熟悉了PVector類的使用,達到了自己的目的。
下面是效果圖和具體代碼實現:
Mover.pde
class Mover {
// The Mover tracks position, velocity, and acceleration
PVector position;
PVector velocity;
PVector acceleration;
// The Mover's maximum speed
float topspeed;
Mover() {
// Start in the center
position = new PVector(random(width),random(height));
velocity = new PVector(0,0);
topspeed = 5;
}
void update() {
// Compute a vector that points from position to mouse
PVector mouse = new PVector(mouseX,mouseY);
acceleration = PVector.sub(mouse,position);
// Set magnitude of acceleration
//acceleration.setMag(0.2);
acceleration.normalize();
acceleration.mult(0.2);
// Velocity changes according to acceleration
velocity.add(acceleration);
//if keyPressed
if(keyPressed){
if(key == 'a'){
topspeed ++;
}
if(key == 's'){
topspeed --;
}
if(key == 'r'){
topspeed = 5;
}
if(topspeed > 15){
topspeed = 15;
}
if(topspeed < 0){
topspeed = 0;
}
}
// Limit the velocity by topspeed
velocity.limit(topspeed);
// position changes by velocity
position.add(velocity);
}
void display() {
stroke(0);
strokeWeight(2);
fill(127,200);
ellipse(position.x,position.y,48,48);
line(mouseX,mouseY,position.x,position.y);
}
}
sketch_1.pde
Mover[] movers = new Mover[20];
void setup() {
size(1200,800);
for (int i = 0; i < movers.length; i++) {
movers[i] = new Mover();
}
}
void draw() {
background(255);
for (int i = 0; i < movers.length; i++) {
movers[i].update();
movers[i].display();
}
}
關於代碼
本次習作運用了面向對象編程的思想。
在Mover類中實現了運動物體的所有事件,包括鼠標和鍵盤與Mover的交互,Mover趨向於靠近鼠標位置,以及Mover中心位置與鼠標位置的連線,體現了鼠標牽引Mover的效果,鍵盤控制最大速度,控制移動效果。
在sketch_1中實現的是畫布的創建,對象的創建以及對象調用函數去實現效果。
加速度影響速度,速度影響位置,最終做到的就是影響Mover的運動,而加速度、速度和位置都是向量。
這些就是關於向量在運動中的應用的習作內容。