【问题标题】:How to follow the unit when you click the mouse单击鼠标时如何跟随单位
【发布时间】:2020-09-02 18:05:09
【问题描述】:

我需要我的单位在我点击敌人时移动到敌人身上,并在我的单位接触到他时摧毁

为了移动,我使用导航网格和光线投射命中

所有单位都有navmesh代理

敌人按点移动

【问题讨论】:

    标签: c# unity3d navmesh


    【解决方案1】:

    有很多方法可以做到这一点:我给你全局的想法,你适应你的剧本 我已将敌人的图层设置为“敌人”,以确保追逐点击的敌人。在我的示例中层敌人 = 8

    三个阶段:

    第一阶段:点击检测并捕获被点击的游戏对象

    private bool chasing = false;
    public Transform selectedTarget;
    
        if (Input.GetMouseButtonDown(0))
        {
            //Shoot ray from mouse position
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit[] hits = Physics.RaycastAll(ray);
    
            foreach (RaycastHit hit in hits)
            { //Loop through all the hits
                if (hit.transform.gameObject.layer == 8)
                { //Make a new layer for targets
                    //You hit a target!
    
                    selectedTarget = hit.transform.root;
                    chasing = true;//its an enemy go to chase it
                    break; //Break out because we don't need to check anymore
                }
            }
        }
    

    第二阶段:追击敌人。所以你必须使用碰撞器和至少一个刚体,你有很多教程来解释如何检测碰撞。

        if (chasing)
        {
            // here i have choosen a speed of 5f
            transform.position = Vector3.MoveTowards(transform.position, selectedTarget.position, 5f * Time.deltaTime);
        }
    

    使用 OnCollisionEnter(或 InTriggerEnter)在碰撞时销毁

    void OnCollisionEnter(Collision col)
    {
        if (col.gameObject.tag == "enemy")
        {
            Destroy(col.gameObject);
        }
    }
    

    给定的代码是3d游戏的,如果你用的是2d游戏,把代码改成2d就行了,没有困难。

    【讨论】:

      猜你喜欢
      • 2022-01-15
      • 1970-01-01
      • 1970-01-01
      • 2014-06-23
      • 1970-01-01
      • 2019-07-09
      • 1970-01-01
      • 2016-07-02
      • 1970-01-01
      相关资源
      最近更新 更多