Unity3D实现点击物体旋转和拖动

来源:互联网 发布:济宁天拓网络 编辑:程序博客网 时间:2024/05/16 14:03

1选择物体

  1. using UnityEngine;  
  2. using System.Collections;  
  3.   
  4. public class roated : MonoBehaviour {  
  5.     private bool roate;  
  6.     private float RoatedSpeed = 1000.0F;  
  7.     void Start () {  
  8.         roate = false;  
  9.     }  
  10.       
  11.     // Update is called once per frame  
  12.     void Update () {  
  13.       
  14.         if(Input.GetMouseButton(0))  
  15.         {  
  16.             float y = 0;  
  17.               
  18.             y = Input.GetAxis("Mouse X")*RoatedSpeed*Time.deltaTime;  
  19.             if(roate)  
  20.             {  
  21.                 gameObject.transform.Rotate(new Vector3(0,y,0));  
  22.                   
  23.             }  
  24.               
  25.         }  
  26.           
  27.     }  
  28.     void OnMouseDown()  
  29.     {  
  30.           
  31.         roate =true;  
  32.         Debug.Log("collider");  
  33.     }  
  34.     void OnMouseUp()  
  35.     {  
  36.         roate = false;  
  37.         Debug.Log("Out of collider");  
  38.     }  
  39.       
  40. }  


2拖动

  1. using System.Collections;  
  2.   
  3. public class clickmove : MonoBehaviour {  
  4.   
  5.     // Use this for initialization  
  6.     void Start () {  
  7.       
  8.     }  
  9.       
  10.     // Update is called once per frame  
  11.     void Update () {  
  12.       
  13.     }  
  14.       
  15.     //下面的函数是当鼠标触碰到碰撞体或者刚体时调用,我的碰撞体设置是mesh collider,然后别忘了,给这个collider添加物理材质  
  16.       
  17.     //值得注意的是世界坐标系转化为屏幕坐标系,Z轴是不变的  
  18.     IEnumerator OnMouseDown()  
  19.     {  
  20.         //将物体由世界坐标系转化为屏幕坐标系 ,由vector3 结构体变量ScreenSpace存储,以用来明确屏幕坐标系Z轴的位置  
  21.         Vector3 ScreenSpace = Camera.main.WorldToScreenPoint(transform.position);  
  22.         //完成了两个步骤,1由于鼠标的坐标系是2维的,需要转化成3维的世界坐标系,2只有三维的情况下才能来计算鼠标位置与物体的距离,offset即是距离  
  23.         Vector3 offset = transform.position-Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x,Input.mousePosition.y,ScreenSpace.z));  
  24.           
  25.         Debug.Log("down");  
  26.       
  27.         //当鼠标左键按下时  
  28.         while(Input.GetMouseButton(0))  
  29.         {  
  30.             //得到现在鼠标的2维坐标系位置  
  31.             Vector3 curScreenSpace =  new Vector3(Input.mousePosition.x,Input.mousePosition.y,ScreenSpace.z);     
  32.             //将当前鼠标的2维位置转化成三维的位置,再加上鼠标的移动量  
  33.             Vector3 CurPosition = Camera.main.ScreenToWorldPoint(curScreenSpace)+offset;          
  34.             //CurPosition就是物体应该的移动向量赋给transform的position属性        
  35.             transform.position = CurPosition;  
  36.             //这个很主要  
  37.             yield return new WaitForFixedUpdate();  
  38.         }  
  39.           
  40.           
  41.     }  
  42. }  

把脚本拖动物体上面


0 0
原创粉丝点击