NavMesh动态碰撞

今天遇到一个问题,就是如何处理一些动态的障碍物。NavMesh是可以躲避静态的障碍物,NavMeshObstacle的作用就是动态增加障碍。但是有个问题,NavMeshObstacle是圆,连椭圆都不行,所以,只好写一个附属脚本,用圆拼成矩形,就可以了。

using UnityEngine;
using System.Collections;

public class NavMeshObstacleHelper : MonoBehaviour {

	//coordinate
	public float X = 0f;
	public float Y = 0f;
	public float Z = 0f;

	public float Length = 0f;
	public float Width = 0f;
	public float Height = 0f;
	public float Diameter = 0f;

	private int lengthCount = 0;
	private float lengthStep = 0f;
	private int widthCount = 0;
	private float widthStep = 0f;

	private GameObject obstacleArray = null;
	private GameObject obstacle = null;

	void Awake()
	{
		obstacleArray = new GameObject ();
		obstacleArray.name = "NavMeshObstacleArray";

		widthCount = (int)(Width / Diameter);	
		lengthCount = (int) (Length / Diameter);

		if (lengthCount > 1)
		{
			lengthStep = (Length - Diameter * lengthCount) / (lengthCount - 1);
		}
		
		if (widthCount > 1)
		{
			widthStep = (Width - Diameter * widthCount) / (widthCount - 1);
		}

	}
	// Use this for initialization
	void Start () {
		initObstacleArray ();
	}

	private void initObstacleArray()
	{
		Vector3 tempPos = new Vector3 (X, Y, Z);

		for (int i = 0; i < lengthCount; i++)
		{
			for (int j = 0; j < widthCount; j++)
			{
				obstacle = new GameObject ();
				obstacle.transform.position = tempPos;
				obstacle.transform.parent = obstacleArray.transform;

				obstacle.AddComponent <NavMeshObstacle>();
				NavMeshObstacle navMeshObstacle = obstacle.GetComponent<NavMeshObstacle> ();
				if (navMeshObstacle)
				{
					obstacle.GetComponent<NavMeshObstacle> ().radius = Diameter / 2;
					obstacle.GetComponent<NavMeshObstacle> ().height = Height;
				}
				tempPos = new Vector3 (tempPos.x, tempPos.y, tempPos.z + Diameter + widthStep);
			}
			tempPos = new Vector3 (tempPos.x + Diameter + lengthStep, tempPos.y,  Z);
		}

		obstacleArray.transform.parent = this.transform;
		obstacleArray.transform.localRotation = Quaternion.identity;
		obstacleArray.transform.position = this.transform.position;

	}

	// Update is called once per frame
	void Update () {
	
	}
}

思路来源自http://www.cnblogs.com/sifenkesi/p/4004215.html

可以看一下,效果:

参数设置





  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值