一、通过鼠标点击,物体跟着移动(RayTest文本)

  //射线(通过点击鼠标,物体跟着移动)

  //1.Plane 添加标签Ground;只有对地面才打印信息,点其他的无效

  //2、对胶囊体、物体添加character Controller组件和刚体,,获取组件在start里添加一次就行,文件给了胶囊体。

-------------------------------------------------------------------------------------------------------------------------------------

   privateCharacterController m_CharacterController;

   privateVector3 target;

1.void Start () {

        m_CharacterController =GetComponent<CharacterController>();//获取组件

        target = transform.position;   //目标

}

2.void Update () {

        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);//通过相机获取一个鼠标点,得到射线

        RaycastHit hit;  //射线点

        if(Physics.Raycast(ray,out hit))

        {

            if(Input.GetMouseButtonDown(0) &&hit.collider.CompareTag("Ground"))//鼠标点下,并且点地面才有效

            {            

                    target = hit.point + newVector3(0, 1, 0);

             }

        }

        transform.position = Vector3.Lerp(transform.position, target, 0.1f);//在平面点击鼠标,物体跟着鼠标移动。

        transform.LookAt(target);                 //平面点击鼠标,物体旋转看向点击点,再移动 

  }

Unity17--鼠标点击物体跟着移动、分层点击移动、铰链(关节)、布料

二、分层点击鼠标,物体跟着移动

   //上面的例子分层(比如在绿层点击物体跟着移动,在红层不移动)(FengCeng文件)

   //2.分层显示:再拼接一块平面场地,左边green 右边Red,只在绿色层移动,红色不移动,先在面板中layer添加green red,再记得点上

   //下面的只替换上个RayTest的这一句就行

privateCharacterController m_CharacterController;

privateVector3 target;

1.void Start () {

        m_CharacterController =GetComponent<CharacterController>();//获取组件

       target = transform.position;//目标

 }

2. void Update()

    {

        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);//通过相机获取一个鼠标点,得到射线

        RaycastHit hit;//射线点

        if (Physics.Raycast(ray, out hit, 100, 1 << 8))//100是最大距离,如果红色也移动,加上| 1 << 9后边是第8层和第9

        {

            if (Input.GetMouseButtonDown(0))//鼠标点下,并且点地面才有效

            {           

                 // 用Lerp好用些

                target = hit.point + newVector3(0, 1, 0);

            }

        }

        transform.position = Vector3.Lerp(transform.position, target, 0.1f);//在平面点击鼠标,物体跟着鼠标移动。

        transform.LookAt(target);//平面点击鼠标,物体旋转看向点击点,再移动 

  }

下面的动态图是加上| 1 << 9的,就是在红色区域第9层也能运动

Unity17--鼠标点击物体跟着移动、分层点击移动、铰链(关节)、布料

三、

1.、铰链,关节(做开关门动作时可用,可参考博客吊桥哪个)

        //physics里添加Hinge.Joint--关节,可把物体拖进去

2.、.布料(可做国旗,或者动的布)

流程:

        //1.布料1、建个平面、用材质球添加可找图片用材质球添加

        //2.添加组件Cloth,设置在SKinned Mesh Renderer mesh-plan --Edit constraints --有几个点,随便框几个点,固定就掉不

             下去了,不固定会滑落,

        3找最底下的Sphere Colliders size可改为1看着改,建两个小球拖进去,运行即可,如果露着圆球的白色可把小球的Mesh 

              Renderer√去掉就变透明了。

Unity17--鼠标点击物体跟着移动、分层点击移动、铰链(关节)、布料



相关文章: