美文网首页
Unity 地面上拖动物体,屏幕UI跟随物体

Unity 地面上拖动物体,屏幕UI跟随物体

作者: 玄策丶 | 来源:发表于2021-02-24 11:25 被阅读0次
/***********************
* Title:        
* FileName:         
* Date:         2020
* Author:       玄策
* Version:      1.0
* UnityVersion: 2019.2.4f1
* Description:  
* Func:           
* -   
***********************/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class clickSheBei : MonoBehaviour
{
    Ray ray;
    RaycastHit hit;
 public transform ui;
    float x1;
    float z1;

    void Update()
    {
        Vector3 v1 = transform.position;
       ui.transform.localPosition = Camera.main.WorldToScreenPoint(new Vector3(v1.x, v1.y, v1.z)); //世界坐标转屏幕坐标
        ui.transform.localPosition -= new Vector3(960, 40, 0); //减去分辨率的一半(分辨率1920*1080),因为父物体y轴为-500,所以y只减40


    }
    private void OnMouseDown()
    {
        Debug.Log("按下");
        BottomTest.Instance.Obj = gameObject;

        BottomTest.Instance.Tr_Bottom.gameObject.SetActive(true);

        ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        if (Physics.Raycast(ray, out hit))
        {
            x1 = hit.point.x - transform.position.x;
            z1 = hit.point.z - transform.position.z;

        }

    }
    private void OnMouseDrag()
    {
        Debug.Log("拖拽");
        ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        if (Physics.Raycast(ray, out hit))
        {
            float x = hit.point.x - x1;
            float z = hit.point.z - z1;

            transform.position = new Vector3(x, transform.position.y, z);

        }
    }
    private void OnMouseUp()
    {
        x1 = 0;
        z1 = 0;
    }
}

相关文章

网友评论

      本文标题:Unity 地面上拖动物体,屏幕UI跟随物体

      本文链接:https://www.haomeiwen.com/subject/jgzqtltx.html