- Unity 5.x Game AI Programming Cookbook
- Jorge Palacios
- 309字
- 2021-07-09 19:37:49
Shooting a projectile
This is the stepping stone for scenarios where we want to have control over gravity-reliant objects, such as balls and grenades, so we can then predict the projectile's landing spot, or be able to effectively shoot a projectile at a given target.
Getting ready
This recipe differs slightly as it doesn't rely on the base AgentBehaviour
class.
How to do it...
- Create the
Projectile
class along with its member variables to handle the physics:using UnityEngine; using System.Collections; public class Projectile : MonoBehaviour { private bool set = false; private Vector3 firePos; private Vector3 direction; private float speed; private float timeElapsed; }
- Define the
Update
function:void Update () { if (!set) return; timeElapsed += Time.deltaTime; transform.position = firePos + direction * speed * timeElapsed; transform.position += Physics.gravity * (timeElapsed * timeElapsed) / 2.0f; // extra validation for cleaning the scene if (transform.position.y < -1.0f) Destroy(this.gameObject);// or set = false; and hide it }
- Finally, implement the
Set
function in order to fire the game object (for example, calling it after it is instantiated in the scene):public void Set (Vector3 firePos, Vector3 direction, float speed) { this.firePos = firePos; this.direction = direction.normalized; this.speed = speed; transform.position = firePos; set = true; }
How it works...
This behavior uses high-school physics in order to generate the parabolic movement.
There's more...
We could also take another approach: implementing public properties in the script or declaring member variables as public and, instead of calling the Set
function, having the script disabled by default in the prefab and enabling it after all the properties have been set. That way, we could easily apply the object pool pattern.
See also
For further information on the object pool pattern, please refer to the following Wikipedia article and an official Unity Technologies video tutorial available online at the following addresses:
- Google Visualization API Essentials
- 計(jì)算機(jī)信息技術(shù)基礎(chǔ)實(shí)驗(yàn)與習(xí)題
- SQL查詢:從入門到實(shí)踐(第4版)
- Neural Network Programming with TensorFlow
- Sybase數(shù)據(jù)庫在UNIX、Windows上的實(shí)施和管理
- Spark大數(shù)據(jù)編程實(shí)用教程
- 大數(shù)據(jù)技術(shù)入門
- 達(dá)夢數(shù)據(jù)庫運(yùn)維實(shí)戰(zhàn)
- 企業(yè)級(jí)容器云架構(gòu)開發(fā)指南
- 數(shù)字IC設(shè)計(jì)入門(微課視頻版)
- SAS金融數(shù)據(jù)挖掘與建模:系統(tǒng)方法與案例解析
- 實(shí)用數(shù)據(jù)結(jié)構(gòu)
- SIEMENS數(shù)控技術(shù)應(yīng)用工程師:SINUMERIK 840D-810D數(shù)控系統(tǒng)功能應(yīng)用與維修調(diào)整教程
- openGauss數(shù)據(jù)庫核心技術(shù)
- 數(shù)據(jù)應(yīng)用工程:方法論與實(shí)踐