您的位置:首页 > 其它

射线 鼠标控制物体前进

2017-11-08 15:13 127 查看
using System.Collections;

using System.Collections.Generic;

using UnityEngine;

public class playercontrol : MonoBehaviour

{

    //1.获取鼠标点击位置

    //通过射线来实现

    //2.让当前目标移动到目标位置

    private Vector3 target;//获取目标位置

    //private bool panduan = t;

    public float speed;

    void Start()

    {

    }

    // Update is called once per frame

    void Update()

    {

        if (Input.GetMouseButtonDown(1))

        {

            //创建射线,从主摄像机发射射线

            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

            //发射射线

            RaycastHit h = new RaycastHit();//存储碰撞信息

            if(Physics.Raycast(ray,out h))//检测信息,如果调用h或者下面的hits必须先检测

            {

                target = h.point;

                target.y = 0.5f;

            }

            //RaycastHit[] hits = Physics.RaycastAll(ray);

            //    for (int i = 0; i < hits.Length; i++)

            //    {

            //        if (Physics.Raycast(ray, out hits[i]))

            //        {

            //            if (hits[i].collider.name == "Plane")

            //            {

            //                target = hits[i].point;

            //                target.y = 0.5f;

            //            }

            //        }

            //    }

        }

        move(target);

    }

    //让目标移动到角色位置

    private void move(Vector3 tar)

    {

        if (Vector3.Distance(transform.position, tar) > 0.1f)

        {

            Vector3 i = tar - transform.position;

            transform.position += i.normalized * speed * Time.deltaTime;

        }

        else

        {

            transform.position = tar;

        }

    }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: