根据鼠标点击位置移动物体

来源:互联网 发布:预谋dj网络歌手加快版 编辑:程序博客网 时间:2024/05/21 09:48
using UnityEngine;
using System.Collections;
using System.Collections.Generic;


public class translateByMouse : MonoBehaviour {




    public GameObject moveObj;
    private List<Vector3> pArr;
    private int len;
    private float s;
    private float dis;
    private float speed = 3;
    private float speedX;
    private float speedY;
    private float angle;
    private bool flag;
    private Vector3 screenV;


// Use this for initialization
void Start () {
        pArr = new List<Vector3>();
        screenV = Camera.main.WorldToScreenPoint(moveObj.transform.position);
}



    void moveCount()
    {
        Vector3 p = pArr[0];
        Vector3 v = moveObj.transform.position;
        float dx = p.x - v.x;
        float dy = p.y - v.y;
        s = Mathf.Sqrt(dx * dx + dy * dy);
        angle = Mathf.Atan2(dy, dx);
        speedX = speed * Mathf.Cos(angle);
        speedY = speed * Mathf.Sin(angle);
        dis = 0;
        flag = true;
        pArr.RemoveAt(0);
    }




// Update is called once per frame
void Update () {


        if (Input.GetMouseButtonDown(0))
        {
            Vector3 dianV = Input.mousePosition;
            dianV.z = screenV.z;
            Vector3 wv = Camera.main.ScreenToWorldPoint(dianV);
            pArr.Add(wv);
            if (!flag)
            {
                moveCount();
            }        
        }




        if (flag)
        {
            moveObj.transform.Translate(Vector3.right * Time.deltaTime * speedX);
            moveObj.transform.Translate(Vector3.up * Time.deltaTime * speedY);
            dis += Time.deltaTime * speed;
            if (dis > s)
            {
                if (pArr.Count > 0)
                {
                    moveCount();             
                }
                else
                {
                    flag = false;
                }
            }
          
        }
}
}
阅读全文
0 0
原创粉丝点击