IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 游戏开发 -> 用Unity实现KD树 -> 正文阅读

[游戏开发]用Unity实现KD树

思路

看他的文章:
https://blog.csdn.net/silangquan/article/details/41483689


KD树是二叉树, 写代码分为2步: 树的建立 和 最近搜索
乍一看, 光树的建立就要遍历好几遍, 效率还不如直接挨个点遍历一遍来的快, 那么, 什么情况下用KD树呢?
答: 在数据庞大且静态的时候
数据量小的时候, 直接遍历搜索就行了, 没必要用KD树
建立树的代价很高, 最好是一旦建立就不再变了. 如果是动态的数据, 点位要频繁更新的话, 也不适合用KD树

代码

代码写的贼乱, 懒得整理了, 主要是理解其中的思路

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public enum SortType
{
    X,
    Y
}

[Serializable]
public class Branch
{
    public Vector2 pos;
    public SortType sortType;
    public Branch left;
    public Branch right;
}

public class HKDTree : MonoBehaviour
{
    public Transform canvas;
    Image tarImage;
    Image closerImage;
    List<Image> images = new List<Image>();
    List<Vector2> allPos = new List<Vector2>();
    List<Image> lines = new List<Image>();
    Image prefabH;
    Image prefabV;

    void Start()
    {
        Init();
    }

    void Init()
    {
        Image prefab = Resources.Load<Image>("Dot");
        Image targetPrefab = Resources.Load<Image>("Target");
        prefabH = Resources.Load<Image>("LineH");
        prefabV = Resources.Load<Image>("LineV");

        for (int i = 0; i < 5; i++)
        {
            Image tr = Instantiate(prefab, canvas);
            images.Add(tr);
        }

        tarImage = Instantiate(targetPrefab, canvas);

        closerImage = Instantiate(prefab, canvas);
        closerImage.color = Color.green;
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            DO();
        }
    }
    void DO()
    {
        allPos.Clear();
        for (int i = 0; i < images.Count; i++)
        {
            Vector2 pos = new Vector2(UnityEngine.Random.Range(-500, 500), UnityEngine.Random.Range(-500, 500));
            images[i].transform.localPosition = pos;
            allPos.Add(pos);
        }

        Vector2 tarPos = new Vector2(UnityEngine.Random.Range(-500, 500), UnityEngine.Random.Range(-500, 500));
        tarImage.transform.localPosition = tarPos;

        for (int i = 0; i < lines.Count; i++)
        {
           Destroy( lines[i].gameObject);
        }
        lines.Clear();
        Branch root = GetBranch(allPos);
        Search(root, tarPos);
        Branch closer = GetCloser(tarPos);

        closerImage.transform.localPosition = closer.pos;
    }

    Branch GetBranch(List<Vector2> poss)
    {
        if (poss.Count == 0)
        {
            return null;
        }
        SortType sortType = SortType.X;
        Vector2 mid = GetMid(poss, out sortType);
        poss.Remove(mid);
        List<Vector2> lefts = new List<Vector2>();
        List<Vector2> rights = new List<Vector2>();
        if (sortType == SortType.X)
        {
            Image line = Instantiate(prefabV, canvas);
            line.transform.localPosition = mid;
            lines.Add(line);
            for (int i = 0; i < poss.Count; i++)
            {
                if (poss[i].x < mid.x)
                {
                    lefts.Add(poss[i]);
                }
                else
                {
                    rights.Add(poss[i]);
                }
            }
        }
        else if (sortType == SortType.Y)
        {
            Image line = Instantiate(prefabH, canvas);
            line.transform.localPosition = mid;
            lines.Add(line);
            for (int i = 0; i < poss.Count; i++)
            {

                if (poss[i].y < mid.y)
                {
                    lefts.Add(poss[i]);
                }
                else
                {
                    rights.Add(poss[i]);
                }
            }
        }
        Branch branch = new Branch();
        branch.pos = mid;
        branch.sortType = sortType;
        branch.left = GetBranch(lefts);
        branch.right = GetBranch(rights);
        return branch;
    }

    Vector3 GetMid(List<Vector2> v, out SortType sortType)
    {
        float x = 0;
        float y = 0;
        float temp1 = 0;
        float temp2 = 0;
        int count = v.Count;
        for (int i = 0; i < count; i++)
        {
            temp1 += 1f / count * v[i].x * v[i].x;
            temp2 += 1f / count * v[i].x;
        }
        x = temp1 - temp2 * temp2;

        temp1 = 0;
        temp2 = 0;
        for (int i = 0; i < count; i++)
        {
            temp1 += 1f / count * v[i].y * v[i].y;
            temp2 += 1f / count * v[i].y;
        }
        y = temp1 - temp2 * temp2;

        //通过计算方差, 确定是用x还是y区分
        if (x > y)
        {
            sortType = SortType.X;
            v.Sort((a, b) => { return a.x.CompareTo(b.x); });
        }
        else
        {
            sortType = SortType.Y;
            v.Sort((a, b) => { return a.y.CompareTo(b.y); });
        }
        return v[count / 2];
    }

    Stack<Branch> branchStack = new Stack<Branch>();
    void Search(Branch branch, Vector2 pos)
    {
        if (branch == null)
        {
            return;
        }
        branchStack.Push(branch);
        if (branch.sortType == SortType.X)
        {
            if (pos.x < branch.pos.x)
            {
                Search(branch.left, pos);
            }
            else
            {
                Search(branch.right, pos);
            }
        }
        else if (branch.sortType == SortType.Y)
        {
            if (pos.y < branch.pos.y)
            {
                Search(branch.left, pos);
            }
            else
            {
                Search(branch.right, pos);
            }
        }
    }

    Branch  (Vector3 pos)
    {
        Branch closer = branchStack.Pop();
        float closerDis = Vector2.Distance(closer.pos, pos);
        while (branchStack.Count != 0)
        {
            Branch branch = branchStack.Pop();
            if (branch == null)
            {
                continue;
            }
            float dis = Vector2.Distance(branch.pos, pos);
            if (dis < closerDis)
            {
                closerDis = dis;
                closer = branch;
            }
            if (branch.sortType == SortType.X)
            {
                //圆与直线相交
                if (dis > Mathf.Abs(branch.pos.x - pos.x))
                {
                    if (pos.x < branch.pos.x)
                    {
                        branchStack.Push(branch.right);
                    }
                    else
                    {
                        branchStack.Push(branch.left);
                    }
                }
            }
            else if (branch.sortType == SortType.Y)
            {
                if (dis > Mathf.Abs(branch.pos.y - pos.y))
                {
                    if (pos.y < branch.pos.y)
                    {
                        branchStack.Push(branch.right);
                    }
                    else
                    {
                        branchStack.Push(branch.left);
                    }
                }
            }
        }
        return closer;
    }
}
  游戏开发 最新文章
6、英飞凌-AURIX-TC3XX: PWM实验之使用 GT
泛型自动装箱
CubeMax添加Rtthread操作系统 组件STM32F10
python多线程编程:如何优雅地关闭线程
数据类型隐式转换导致的阻塞
WebAPi实现多文件上传,并附带参数
from origin ‘null‘ has been blocked by
UE4 蓝图调用C++函数(附带项目工程)
Unity学习笔记(一)结构体的简单理解与应用
【Memory As a Programming Concept in C a
上一篇文章           查看所有文章
加:2021-08-10 13:46:02  更:2021-08-10 13:47:25 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年5日历 -2024/5/8 23:53:17-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码