Sunday 27 September 2015

Shot Prediction

Phew. After a long, exhausting day taking a refresher course on geometry/vectors, we have a shot prediction calculation to give the goalie some diving AI.

Thanks to Mr Chong for his article:

http://code.tutsplus.com/tutorials/predicting-collision-points-with-math-in-as3--active-11218

The goalie isn't programmed yet, but the important thing is we can predict where the shot is going to cross the goal line (or any other line for that matter):



Here's some code:

1:  Point CollisionDetector::predict_intersection(const Point& position, const Math::Vector3 &direction, const Line &line, bool right_normal){  
2:   Point intersection;  
3:    
4:   // head of ball is position  
5:   Point ball_head = position;  
6:   // tail of ball is position plus direction  
7:   Point ball_tail(position.x + direction.x, position.y + direction.y);  
8:    
9:   // head of line is start of line  
10:   Point line_head(line.x, line.y);  
11:   // tail of line is end of line  
12:   Point line_tail(line.x + line.w, line.y);  
13:    
14:   Math::Vector3 vball(ball_tail.x - ball_head.x, ball_tail.y - ball_head.y);  
15:   Math::Vector3 vline(line_tail.x - line_head.x, line_tail.y - line_head.y);  
16:    
17:   // toV2b is vector from point to start of line  
18:   double perp1 = vball.perpProduct(vline.normalised());  
19:   Math::Vector3 toV2b(line_head.x - ball_head.x, line_head.y - ball_head.y);  
20:   double perp2 = toV2b.perpProduct(vline.normalised());  
21:    
22:   /*  
23:   * length is calculated from the similar triangles ratio  
24:   * it is later used as magnitude for a vector  
25:   * that points in v1's direction  
26:   */  
27:   double length = perp2 / perp1 * vball.magnitude();  
28:   Math::Vector3 length_v1 = vball;  
29:   length_v1 = length_v1 * length;  
30:    
31:   /*  
32:   * extend to locate the exact location of collision point  
33:   */  
34:   intersection.x = ball_head.x + length_v1.x;  
35:   intersection.y = ball_head.y + length_v1.y;  
36:    
37:   return intersection;  
38:  }  

No comments:

Post a Comment