
同學期中作品範例:射擊遊戲
首先
先把食指找到並畫出來

程式碼:
import de.voidplus.leapmotion.*;
LeapMotion leap;
void setup(){
size(600,400,P3D);
leap = new LeapMotion(this);
}
void draw(){
background(255);
for(Hand hand : leap.getHands()){
Finger finger_index = hand.getIndexFinger();//找到手指
finger_index.draw();//畫手指
}
}
打完程式之後
你會發現有一行紅紅的字
那是因為未加上3D的效果(橘色螢光筆地方)
完成之後 紅色的字就不見了
在畫面上畫出一個長方體
以測試他的3D效果

射擊遊戲
顧名思義當然要有東西射出去啊
所以要先有一把槍才有東西可以射
所以就先用球來做出一把長長的槍

程式碼:
import de.voidplus.leapmotion.*;
LeapMotion leap;
void setup(){
size(600,400,P3D);
leap = new LeapMotion(this);
}
PVector pos = null,dir = null;
void draw(){
background(255);
for(Hand hand : leap.getHands()){
Finger finger_index = hand.getIndexFinger();//find finger
finger_index.draw();//draw finger
pos = finger_index.getPosition();//手指位置
dir = finger_index.getDirection();//手指方向
}
lights();
fill(255,0,0);
pushMatrix();
translate(width/2,height/2);
for(int i=0;i<10;i++){
if(dir!=null) translate(dir.x*10*i,dir.y*10*i,dir.z*10*i);
sphere(40);//畫球球槍
}
popMatrix();
}
而槍不能射子彈就沒用處了
所以接著我們要做射子彈


程式碼:
import de.voidplus.leapmotion.*;
PVector pos = null, dir = null;
PVector []bullet = new PVector[10];
PVector []bullet_dir = new PVector[10];
int bulletNow = 0;
LeapMotion leap;
void setup() {
size(600, 400, P3D);
leap = new LeapMotion(this);
for (int i=0; i<10; i++)
{
bullet[i] = new PVector(0, 0, 0);
bullet_dir[i] = new PVector(0, 0, 0);
}
}
void draw() {
background(255);
for (Hand hand : leap.getHands ()) {
Finger finger_index = hand.getIndexFinger();//find finger
finger_index.draw();//draw finger
dir = finger_index.getDirection();
}
lights();
fill(255, 0, 0);
translate(width/2, height/2);
pushMatrix();
for (int i=0; i<10; i++) {
if (dir!=null) translate(dir.x*10*i, dir.y*10*i, dir.z*10*i);
sphere(40);
}
popMatrix();
pushMatrix();
fill(0, 0, 255);
for (int i=0; i<10; i++) {
pushMatrix();
translate(bullet[i].x, bullet[i].y, bullet[i].z);
sphere(41);
bullet[i].x += bullet_dir[i].x;
bullet[i].y += bullet_dir[i].y;
bullet[i].z += bullet_dir[i].z;
popMatrix();
}
popMatrix();
}
void keyPressed() {
bullet_dir[bulletNow].x = dir.x*5;
bullet_dir[bulletNow].y = dir.y*5;
bullet_dir[bulletNow].z = dir.z*5;
bulletNow++;
if(bulletNow>=10){
bulletNow = 0;
}
}
接著我們要做的是棒子打到球的碰撞偵測
若球棒碰到球則背景變紅色
程式碼:
import de.voidplus.leapmotion.*;
LeapMotion leap;
PVector pos,dir,ball;
void setup(){
size(600,400,P3D);
leap = new LeapMotion(this);
pos = new PVector(300,200,0); ball = new PVector(0,0,0);
}
void draw(){
ball.x +=2;ball.y +=2;
for(Hand hand :leap.getHands()){
pos = hand.getPosition();
}
background(255);
fill(255,0,0);
pushMatrix();
translate(pos.x,pos.y,pos.z);
box(30,30,30);
popMatrix();
pushMatrix();
translate(ball.x,ball.y);
sphere(30);
if(dist(ball.x,ball.y,pos.x,pos.y)<30) background(255,0,0);
popMatrix();
}
沒有留言:
張貼留言