臨近期末要開始準備作品了,所以這星期咱要返璞歸真,回到P語言圖學上,可能會對我們的期末作品有幫助,首先我們先回到矢量顯示圖片的功能上,原理和期中考前我們學過的差不多,只是結構稍微複雜了一些,程式碼如下:
size(775,1000);
PImage
img=loadImage("img.png");
PVector
user=new PVector(10,20,0);
PVector
user2=new PVector(30,40,50);
image(img,0,0);
print("user's="+user.x);
println("
user2's="+user2.x);
這樣就可以展示出某部70年代經典電影的海報了
所以其實矢量坐標的觀念和我們在圖學中接觸過的十分相似,那通過這個方式我們也可以利用坐標軸將我們需要的圖形設定在特定位置,例如我可以讓一個半徑為5的圓產生在(100,100)的位置,程式碼如下:
PVector user;
void setup()
{
size(600,600);
user=new PVector(100, 100);
}
void draw()
{
background(255);
ellipse(user.x,user.y,50,50);
}
真的可以説是夢回圖學了
接下來老師教了我們如何使用P寫出Angry Bird的彈弓發射程式,雖是簡化版的但基本有彈弓發射的雛形,要是加上牛頓原理會更逼真,代碼如下:
PVector user;
PVector Y,v=null;
void setup()
{
size(600,600);
user=new PVector(100, 300);
Y= new PVector(100,300);
}
void draw()
{
background(255);
line(user.x,user.y,Y.x,Y.y);
textSize(40);
fill(255,0,0);text("Y",Y.x,Y.y);
fill(255); ellipse(user.x,user.y,20,20);
if(v!=null)
user.add(v);
}
void mouseDragged()
{
user.x=mouseX;
user.y=mouseY;
}
void mouseReleased()
{
PVector diff = PVector.sub(Y, user);
v=diff.div(10);
}
但生成的結果綫會一直連著,所以我感覺相對彈弓這更像投石索
現在我們要給游戲加上新功能,使用搖桿操作彈弓,所以理論上我們需要UNO可以回傳搖桿的坐標值給此時的Processing使用,所以我們要先使用如下的程式碼:
void setup()
{
pinMode(2,INPUT_PULLUP);
Serial.begin(9600);
}
void loop()
{
int x = analogRead(A0);
int y = analogRead(A1);
int sw = analogRead(2);
Serial.write(x/4);
Serial.write(y/4);
Serial.write(sw);
delay(20);
}
然後我們需要測試一下是否可以在Processing中正常運行,使用如下的程式碼測試⚪的移動軌跡就可以了:
假如把殘影打開的話可以產生連點呈現的效果
最後只要把這兩部合并,放在剛剛寫出的彈弓上,就是我們要的最終效果了:
import processing.serial.*;
Serial myport;
PVector user;
PVector Y,v=null;
void setup()
{
size(600,400);
myport = new Serial(this,"COM3",9600);
user = new PVector(100,300);
Y = new PVector(100,300);
}
void draw()
{
background(255);
if(myport.available()>=3)
{
int x = myport.read();
int y = myport.read();
int sw = myport.read();
user.x = 100+x-128;
user.y = 900+y-128;
}
textSize(40);
fill(255,0,0); text("Y",Y.x,Y.y);
fill(255); ellipse(user.x,user.y,20,20);
if(v!=null)
{
user.add(v);
v.y+=9.8;
}
}
這樣就是最後的效果,不過好像⚪飛的太快了
這就是這星期我們學到内容,接下來要進行期末作業製作,這個確實可以給人提供不少項目的靈感。

























