SHOW:
|
|
- or go back to the newest paste.
| 1 | //@AstarPro | |
| 2 | using UnityEngine; | |
| 3 | using System.Collections; | |
| 4 | using Pathfinding; | |
| 5 | ||
| 6 | /** Attach to any GameObject and the object will be clamped to the navmesh. | |
| 7 | * If a GameObject has this component attached, one or more graph linecasts will be carried out every frame to ensure that the object | |
| 8 | * does not leave the navmesh area.\n | |
| 9 | * It can be used with GridGraphs, but Navmesh based ones are prefered. | |
| 10 | * | |
| 11 | * \note This has partly been replaced by using an RVOController along with RVONavmesh. | |
| 12 | * It will not yield exactly the same results though, so this script is still useful in some cases. | |
| 13 | * | |
| 14 | * \astarpro */ | |
| 15 | public class NavmeshClamp : MonoBehaviour {
| |
| 16 | ||
| 17 | Node prevNode; | |
| 18 | Vector3 prevPos; | |
| 19 | ||
| 20 | // Update is called once per frame | |
| 21 | void LateUpdate () {
| |
| 22 | ||
| 23 | if (prevNode == null) {
| |
| 24 | NNInfo nninfo = AstarPath.active.GetNearest (transform.position); | |
| 25 | prevNode = nninfo.node; | |
| 26 | prevPos = transform.position; | |
| 27 | ||
| 28 | } | |
| 29 | ||
| 30 | if (prevNode == null) {
| |
| 31 | return; | |
| 32 | } | |
| 33 | ||
| 34 | if (prevNode != null) {
| |
| 35 | ||
| 36 | ||
| 37 | IRaycastableGraph graph = AstarData.GetGraph (prevNode) as IRaycastableGraph; | |
| 38 | if (graph != null) {
| |
| 39 | GraphHitInfo hit; | |
| 40 | if (graph.Linecast (prevPos,transform.position,prevNode, out hit)) {
| |
| 41 | hit.point.y = transform.position.y; | |
| 42 | Vector3 closest = Mathfx.NearestPoint (hit.tangentOrigin,hit.tangentOrigin+hit.tangent,transform.position); | |
| 43 | Vector3 ohit = hit.point; | |
| 44 | - | ohit = ohit + Vector3.ClampMagnitude((Vector3)hit.node.position-ohit,0.01f); |
| 44 | + | ohit = ohit + Vector3.ClampMagnitude((Vector3)hit.node.position-ohit,0.008f); |
| 45 | if (graph.Linecast (ohit,closest,hit.node, out hit)) {
| |
| 46 | hit.point.y = transform.position.y; | |
| 47 | transform.position = hit.point; | |
| 48 | } else {
| |
| 49 | closest.y = transform.position.y; | |
| 50 | ||
| 51 | transform.position = closest; | |
| 52 | } | |
| 53 | } | |
| 54 | prevNode = hit.node; | |
| 55 | } | |
| 56 | } | |
| 57 | ||
| 58 | prevPos = transform.position; | |
| 59 | } | |
| 60 | } |