AI簡單平移追蹤算法

1.比較座標追蹤法算法

追蹤者會不停地比較自身和目標的x座標和y座標,每x和y上一個單位的移動爲一個週期,該算法雖然簡單好用,但實用性差且不智能化,若是追蹤者數量增長,路線會顯得單調,因爲都是先走個對角線再一路直行,極可能形成多個追蹤者擁堵在一塊兒。dom

代碼:spa

 1 while(!(rigesha.x==killer.x&&rigesha.y==killer.y)){
 2 
 3    if(rigesha.x>killer.x){
 4    killer.goRight();
 5    }else if(rigesha.x<killer.x){
 6    killer.goLeft();
 7    }
 8 
 9    if(rigesha.y>killer.y){
10    killer.goDown();
11    }else if(rigesha.y<killer.y){
12    killer.goUp();
13    }
14 
15 }

 

2.射線動態追蹤法code

先在追蹤者和目標之間創建一條直線,如圖所示,而後再經過三角形面積公式法,模擬上行或左行一個單位後,距離該直線的距離,比較這兩個距離,執行最短距離所對應的操做。blog

這樣一來,追蹤路線會盡量接近直線,AI效果會更逼真。class

在追蹤過程當中,若是監測到目標改變位置(此例假設目標每一幀都逃跑),那麼追蹤者就會從新創建二者之間的直線,而後沿着該直線繼續追蹤(如圖所示)。float

代碼:im

 1 rigeshaX = rigesha.x;
 2 rigeshaY = rigesha.y;
 3 killerX = killer.x;
 4 killerY = killer.y; 
 7 while(!(rigesha.x==killer.x&&rigesha.y==killer.y)){
 8 
 9    if(Random(0,1)>0.5){
10    if(rigesha.x>killer.x){rigesha.goRight();}else{rigesha.goLeft();}
11    }else{
12    if(rigesha.y>killer.y){rigesha.goDown();}else{rigesha.goUp();}
13    }
14    rigesha.move = true;
15    }
16 
17    if(rigesha.move){
18    caculaterLine();
19    }
20 
21    float rightDistanse = xORy(++killer.x,killer.y);
22    float leftDistance = xORy(--(--killer.x),killer.y);
23    float upDistance = xORy(++killer.x),--killer.y);
24    float downDistance = xORy(killer.x,++(++killer.y));
25    killer.y--;
26 
27    if(rigesha.x<=killer.x&&rigesha.y<=killer.y){
28    if(leftDistance<=upDistance){
29    killer.goLeft();
30    }else{
31    killer.goUp();
32    }
33    rigesha.move = false;
34    continue;
35    }
36 
37    if(rigesha.x>=killer.x&&rigesha.y<=killer.y){
38    if(rightDistance<=upDistance){
39    killer.goRight();
40    }else{
41    killer.goUp();
42    }
43    rigesha.move = false;
44    continue;
45    }
46 
47    if(rigesha.x>=killer.x&&rigesha.y>=killer.y){
48    if(rightDistance<=downDistance){
49    killer.goRight();
50    }else{
51    killer.goDown();
52    }
53    rigesha.move = false;
54    continue;
55    }
56 
57    if(rigesha.x<=killer.x&&rigesha.y>=killer.y){
58    if(leftDistance<=downDistance){
59    killer.goLeft();
60    }else{
61    killer.goDown();
62    }
63    rigesha.move = false;
64    continue;
65    }
66 
67 }
68 
69 void caculaterLine(){
70    rigeshaX = rigesha.x;
71    rigeshaY = rigesha.y;
72    killerX = killer.x;
73    killerY = killer.y;
74 }
75 
76 float xORy(x,y){
77    float S = x*killerY + killerX*rigeshaY + rigeshaX*y - x*rigeshaY - killerX*y - rigeshaX*killerY;
78    if(S<0){S = -S;}
79    float lengthDI = sqrt((killerX-rigashaX)*(killerX-rigashaX)+(killerY-rigashaY)*(killerY-rigashaY))
80    distance = S/lengthDI;
81    return distance;
82 }
相關文章
相關標籤/搜索