我有一個簡單的草圖(在Processing),基本上有一堆點在四處遊蕩,如果他們接觸到對方,他們會打(每個人都有一個實力值,每次贏時增加,如果相等,贏家是隨機的選擇)如何使Processing.org草圖更高效?
它適用於約5000個12像素的「殭屍」(有一個半秒的輕微減速,而殭屍最初相互碰撞),問題是當殭屍變得更小,他們不要相互碰撞,並且減速時間可以更長。
代碼非常簡單 - 基本上每個殭屍都是一個類,它有一個X/Y座標。每幀所有的殭屍都會輕推一個像素,隨機轉動lurching
度(或不)。我認爲緩慢的最大原因是碰撞檢測 - 每個殭屍檢查每隔一個(所以殭屍1檢查2-5000,殭屍2檢查1,3-5000等。)
我想保留所有內容簡單,「簡單處理」(不使用外部庫,這可能是更有效,更容易,但我不覺得學習是非常有用的)
int numZombies = 5000;
Zombie[] zombies = new Zombie[numZombies];
void setup(){
size(512, 512);
noStroke();
for(int i = 0; i < numZombies; i++){
zombies[i] = new Zombie(i, random(width), random(height), random(360), zombies);
}
}
void draw(){
background(0);
for(int i = 0; i < numZombies; i++){
zombies[i].move();
zombies[i].display();
}
}
class Zombie{
int id; // the index of this zombie
float x, y; // current location
float angle; // angle of zombies movement
float lurching = 10; // Amount angle can change
float strength = 2;
boolean dead = false; // true means zombie is dead
float diameter = 12; // How big the zombie is
float velocity = 1.0; // How fast zombie moves
Zombie[] others; // Stores the other zombies
Zombie(int inid, float xin, float yin, float inangle, Zombie[] oin){
id = inid;
x = xin;
y = yin;
angle = inangle;
others = oin;
}
void move(){
if(dead) return;
float vx = velocity * sin(radians(180-angle));
float vy = velocity * cos(radians(180-angle));
x = x + vx;
y = y + vy;
if(x + vx < 0 || x + vx > width || y + vy < 0 || y + vy > height){
// Collided with wall
angle = angle + 180;
}
float adecide = random(3);
if(adecide < 1){
// Move left
angle=angle - lurching;
}
else if(adecide > 1 && adecide < 2){
// Don't move x
}
else if(adecide > 2){
// Move right
angle = angle + lurching;
}
checkFights();
}
void checkFights(){
for (int i=0; i < numZombies; i++) {
if (i == id || dead || others[i].dead){
continue;
}
float dx = others[i].x - x;
float dy = others[i].y - y;
float distance = sqrt(dx*dx + dy*dy);
if (distance < diameter){
fight(i);
}
}
}
void fight(int oid){
Zombie o = others[oid];
//println("Zombie " + id + "(s: "+ strength +") fighting " + oid + "(s: "+ o.strength +")");
if(strength < o.strength){
kill();
o.strength++;
}
else if (strength == o.strength){
if(random(1) > 0.5){
kill();
o.strength++;
}
else{
o.kill();
strength++;
}
}
}
void kill(){
dead = true;
}
void display(){
if(dead) return;
ellipse(x, y, diameter, diameter);
}
}
我曾想過這樣的事情,但對於區域之間的衝突?我的另一個/類似的想法是隻檢查附近的殭屍是否有碰撞,但是你仍然必須檢查每個殭屍的其他位置。 – dbr 2009-01-07 08:47:53