【Unity3D自学记录】用NavMesh实现鼠标点击跟随

来源:互联网 发布:linux虚拟机串口调试 编辑:程序博客网 时间:2024/06/03 19:39



文章中有实现这样的效果,但是没有给出方法,小弟在此演示一下,实现想法来自于之前写过的切水果。。。

1.首先创建一个plane
2.添加direct light
3.添加两个cube,一个为man,一个为target
4.选择plane,Navigation窗口中勾选Navigation Static
5.选中man,添加Navmesh agent


下面给man和target分别添加脚本。。哇咔咔。。

man的,比较简单

[C#] 纯文本查看 复制代码
?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
usingUnityEngine;
usingSystem.Collections;
 
publicclassman : MonoBehaviour {
     
    privateNavMeshAgent manone;
    publicTransform target;
    // Use this for initialization
    voidStart () {
        manone=gameObject.GetComponent<NavMeshAgent>();
         
     
    }
     
    // Update is called once per frame
    voidUpdate () {
        manone.SetDestination(target.position);
     
    }
}





target的脚本

[C#] 纯文本查看 复制代码
?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
usingUnityEngine;
usingSystem.Collections;
 
publicclasstarget : MonoBehaviour {
 
    // Use this for initialization
    voidStart () {
         
     
    }
     
    // Update is called once per frame
    voidUpdate () {
        if(Input.GetMouseButton(0))
        {
            Ray ray=Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;
            if(Physics.Raycast(ray,outhit,100))
            {
                if(hit.collider.tag=="plane")
                {
                    transform.position=hit.point;
  
                }
 
                 
            }
        }
         
     
    }
     
     
}





最后不要忘记把H视图中的target赋值man脚本中的target哦。。赶紧试试吧。。。对了,要记得把target的Mesh Render属性勾选掉
在这里之所以不直接使用Input.mouseposition是为了方便后续的碰撞检测哦。。。

 
0 0
原创粉丝点击