zoukankan      html  css  js  c++  java
  • 在屏幕拖拽3D物体移动

    3D物体的拖拽不同于2D的。因为3D物体有x,y,z当然。实际拖拽还是在XZ平面。只是多了几个转换

     1 using UnityEngine;
     2 using System.Collections;
     3 
     4 public class tuotuo : MonoBehaviour
     5 {
     6 
     7     Vector3 currPosition; //拖拽前的位置
     8     Vector3 newPosition; //拖拽后的位置
     9 
    10     // Use this for initialization
    11     void Start()
    12     {
    13 
    14     }
    15 
    16     // Update is called once per frame
    17     void Update()
    18     {
    19 
    20     }
    21 
    22     /// <summary>
    23     /// 开始拖拽 3D物体 拖拽是在平面拖拽 即 xy平面
    24     /// </summary>
    25     void OnMouseDrag()
    26     {
    27         //1:把物体的世界坐标转为屏幕坐标 (依然会保留z坐标)
    28         currPosition = Camera.main.WorldToScreenPoint(transform.position);
    29 
    30         //2:更新物体屏幕坐标系的x,y
    31         currPosition = new Vector3(Input.mousePosition.x, Input.mousePosition.y, currPosition.z);
    32 
    33         //3:把屏幕坐标转为世界坐标
    34         newPosition = Camera.main.ScreenToWorldPoint(currPosition);
    35 
    36         //4:更新物体的世界坐标
    37         transform.position = newPosition;
    38     }
    39 }
     OnMouseDrag只是MonoBehaviour的一个方法。如果想拖拽UGUI界面是不行的。必须继承接口
    using UnityEngine;
    using System.Collections;
    using DG.Tweening;
    using UnityEngine.UI;
    using System.Collections.Generic;
    using UnityEngine.EventSystems;
    public class newButton : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
    {
      
        //自己的RectTransform
        RectTransform rf;
        //Vector3 oldPosition;//原来的位置,拖拽前的位置
        Vector3 newPosition;//拖拽中的位置
        bool isDrag; //是否开始拖拽
        public void OnEndDrag(PointerEventData eventData)
        {
    
    
        }
    
        public void OnDrag(PointerEventData eventData)
        {
            if (isDrag) //必须要执行了OnBeginDrag才执行OnDrag 有时候会遇到不执行OnBeginDrag
            {
                // 通过屏幕中的鼠标点,获取在父节点中的鼠标点
                RectTransformUtility.ScreenPointToWorldPointInRectangle(rf, eventData.position, eventData.enterEventCamera, out newPosition);
                rf.position = newPosition; //设置拖动的图片的位置
                //print(newPosition);
            }
        }
    
        public void OnBeginDrag(PointerEventData eventData)
        {
            isDrag = true;
        }
  • 相关阅读:
    time 时间模块的函数调用
    str 文本函数的调用
    批量分发公钥
    K8s集群部署(四)------ Flannel网络部署
    kuberbetes基础概念
    K8s集群部署(三)------ Node节点部署
    K8s集群部署(二)------ Master节点部署
    K8s集群部署(一)------ETCD集群部署
    日常更新脚本
    CentOS7系统安装
  • 原文地址:https://www.cnblogs.com/nsky/p/4628359.html
Copyright © 2011-2022 走看看