public class QuickSort : MonoBehaviour
{
private void Start()
{
int[] Nums = { 4, 3, 6, 1, 8, 0, 3, 2, 5, 7};
Sort(Nums, 0, 9);
for (int i = 0; i < 10; i++)
{
Debug.Log(Nums[i]);
}
}
void Sort(int[] nums,int left,int right)
{
//退出条件
if (left >= right)
return;
int i = left;
int j = right;
//中心元素取为第一个元素
int temp = nums[left];
while(i != j)
{
//从最右边的元素开始比较中心元素
while(i < j && nums[j] >= temp)
{
j--;
}
if(i < j )
{
nums[i] = nums[j];
}
while(i < j && nums[i] <= temp)
{
i++;
}
if(i < j)
{
nums[j] = nums[i];
}
}
nums[i] = temp;
Sort(nums, left, i - 1);
Sort(nums, i+1, right);
}
}
public class BubbleSort : MonoBehaviour
{
private void Start()
{
int[] array = { 6, 5, 8, 7, 1, 2, 3, 5 };
Sort(array);
for (int i = 0; i < array.Length; i++)
{
Debug.Log(array[i]);
}
}
private void Sort(int[] array)
{
//进行i次排序,对数组内所有元素都进行比较
for (int i = 0; i < array.Length - 1; i++)
{
//对某一元素进行的相邻元素的比较,比较次数差i次
for(int j = 0; j < array.Length-1-i; j++)
{
if(array[j] > array[j+1])
{
int temp = array[j];
//如果左边的数字比右边的大,就把大的数字向右平移一位
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
}
}
public class BinarySearch : MonoBehaviour
{
private void Start()
{
int[] array = { 8, 11, 21, 28, 32, 43, 48, 56, 69, 72, 80, 94 };
Debug.Log(Search(array, 80));
}
private int Search(int[] array,int key)
{
var min = 0;
var max = array.Length - 1;
var mid = 0;
while(min <= max)
{
mid = (min + max) / 2;
if(array[mid] > key)
{
max = mid - 1;
}
else if(array[mid] < key)
{
min = mid + 1;
}
else if(array[mid] == key)
{
return mid;
}
}
return 0;
}
}
Debug.Log(SearchTwo(array, 80,0,12));
private int SearchTwo(int[] array,int key,int low,int high)
{
if (low > high)
return -1;
var mid = (low + high) >> 1;
if (array[mid] > key)
{
return SearchTwo(array, key, low, mid - 1);
}
else if (array[mid] < key)
{
return SearchTwo(array, key, mid + 1, high);
}
else
return mid;
}
}
我们的目标是简单的选择最低的F代价,不断的重复,直到我们的目标节点
代码部分可以见:
(1条消息) Unity A星(A Star/A*)寻路算法_unity寻路算法_九本才的博客-CSDN博客
现在有A*的寻路插件
优点:目标点在封闭空间内时,BStar效率优势明显
缺点:喜欢贴着墙走
NacigationMesh是一种数据结构,用于描述游戏世界的可行走表面
Navigation是Unity自带的导航,具备基本的Bake,NavMesh和NavMeshAgent等基本导航功能
新版中有NavMeshComponent,能够实现动态烘焙
using UnityEngine;
using UnityEngine.AI;
public class Player : MonoBehaviour
{
private NavMeshAgent agent;
public Transform target;
void Start()
{
agent = GetComponent();
agent.destination = target.position;
}
}