- Unity 5.x Game AI Programming Cookbook
- Jorge Palacios
- 372字
- 2021-07-09 19:37:50
Targeting a projectile
Just like it's important to predict a projectile's landing point, it's also important to develop intelligent agents capable of aiming projectiles. It wouldn't be fun if our rugby-player agents aren't capable of passing the ball.
Getting ready
Just like the previous recipe, we only need to expand the Projectile
class.
How to do it...
Thanks to our previous hard work, this recipe is a real piece of cake:
- Create the
GetFireDirection
function:public static Vector3 GetFireDirection (Vector3 startPos, Vector3 endPos, float speed) { // body }
- Solve the corresponding quadratic equation:
Vector3 direction = Vector3.zero; Vector3 delta = endPos - startPos; float a = Vector3.Dot(Physics.gravity, Physics.gravity); float b = -4 * (Vector3.Dot(Physics.gravity, delta) + speed * speed); float c = 4 * Vector3.Dot(delta, delta); if (4 * a * c > b * b) return direction; float time0 = Mathf.Sqrt((-b + Mathf.Sqrt(b * b - 4 * a * c)) / (2*a)); float time1 = Mathf.Sqrt((-b - Mathf.Sqrt(b * b - 4 * a * c)) / (2*a));
- If shooting the projectile is feasible given the parameters, return a non-zero direction vector:
float time; if (time0 < 0.0f) { if (time1 < 0) return direction; time = time1; } else { if (time1 < 0) time = time0; else time = Mathf.Min(time0, time1); } direction = 2 * delta - Physics.gravity * (time * time); direction = direction / (2 * speed * time); return direction;
How it works...
Given a fixed speed, we solve the corresponding quadratic equation in order to obtain the desired direction (when at least one time value is available), which doesn't need to be normalized because we already normalized the vector while setting up the projectile.
There's more...
Take into account that we are returning a blank direction when time is negative; it means that the speed is not sufficient. One way to overcome this is to define a function that tests different speeds and then shoots the projectile.
Another relevant improvement is to add an extra parameter of the type bool
for those cases when we have two valid times (which means two possible arcs), and we need to shoot over an obstacle such as a wall:
if (isWall) time = Mathf.Max(time0, time1); else time = Mathf.Min(time0, time1);
- GitHub Essentials
- PyTorch深度學習實戰(zhàn):從新手小白到數(shù)據(jù)科學家
- Learning Proxmox VE
- 數(shù)據(jù)中心數(shù)字孿生應用實踐
- SQL Server 2012數(shù)據(jù)庫管理教程
- Chef Essentials
- 數(shù)據(jù)分析師養(yǎng)成寶典
- 二進制分析實戰(zhàn)
- 計算機視覺
- Filecoin原理與實現(xiàn)
- 企業(yè)級大數(shù)據(jù)項目實戰(zhàn):用戶搜索行為分析系統(tǒng)從0到1
- 從Lucene到Elasticsearch:全文檢索實戰(zhàn)
- Kafka權威指南(第2版)
- 達夢數(shù)據(jù)庫集群
- 醫(yī)療大數(shù)據(jù)分析與應用