- 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:
- 數據分析實戰:基于EXCEL和SPSS系列工具的實踐
- Hands-On Machine Learning with Microsoft Excel 2019
- 大數據可視化
- Spark核心技術與高級應用
- 數據驅動設計:A/B測試提升用戶體驗
- INSTANT Cytoscape Complex Network Analysis How-to
- 大數據Hadoop 3.X分布式處理實戰
- “互聯網+”時代立體化計算機組
- Oracle PL/SQL實例精解(原書第5版)
- Hadoop大數據開發案例教程與項目實戰(在線實驗+在線自測)
- 實用數據結構
- 數據庫技術及應用
- Augmented Reality using Appcelerator Titanium Starter
- 數據庫應用系統技術
- 數據中心UPS系統運維