关于这个问题,我总觉得简单很好做,但是拿到手里,却有种有劲儿使不出来的感觉,想了想应该是最近的代码量有点少了!所以大家一定要多写代码啊!就像运动员一样,要多多锻炼才是!(更何况是我这样的新手程序员啊...........)
这里以一个Cube为例吧,首先创建了场景场景中有一个方块,因为主要是想着如何实现功能,所以这里暂时没有考虑性能方面!还请读者能够自己针对性的修改代码。
如下图简单的场景:
废话不多说了,上代码:
1 using UnityEngine; 2 using System.Collections; 3 4 public class Rotate01 : MonoBehaviour { 5 6 public GameObject obj; 7 Ray ray; 8 // Use this for initialization 9 void Start () { 10 obj.transform.parent = null; 11 } 12 private float scrow=0; 13 void Update () { 14 ray = Camera.main.ScreenPointToRay(Input.mousePosition); 15 if (Input.GetMouseButton(0)) 16 { 17 RaycastHit hit; 18 if (Physics.Raycast(ray, out hit)) 19 { 20 if (hit.transform.tag == "cube") 21 { 22 //调试画出的射线 23 Debug.DrawLine(transform.position, hit.point); 24 //观察射线碰撞点 25 Debug.Log(hit.point); 26 //实现鼠标点击不松开,物体跟随鼠标移动,但是效果不怎么好 27 obj.transform.position = new Vector3(hit.point.x, hit.point.y, obj.transform.position.z); 28 //点击变色,就是为了提示哪个被点击了 29 hit.transform.renderer.material.color = Color.red; } 30 } 31 else 32 { 33 obj.transform.parent = null; 34 obj.renderer.material.color = Color.white; 35 } 36 37 } 38 39 if(Input.GetMouseButton(1)) 40 {//控制上下左右旋转 41 obj.transform.Rotate(Vector3.up, -Time.deltaTime * 200 * Input.GetAxis("Mouse X")); 42 obj.transform.Rotate(Vector3.right, Time.deltaTime * 200 * Input.GetAxis("Mouse Y")); 43 } 44 if (Input.GetAxis("Mouse ScrollWheel") != 0&&obj.renderer.material.color==Color.red) 45 { 46 scrow=Input.GetAxis("Mouse ScrollWheel"); 47 obj.transform.position += (transform.position - obj.transform.position).normalized * scrow; 48 } 49 50 51 } 52 }
我现在也只是一个刚入门的程序员,所以代码写的不怎么好,还望包涵哈~~~~
这个就是简单的效果,点中物体后变色,并且能够跟着鼠标一起走了(射线只能在scnce面板中看到)
然后我松开左键,点住右键,物体随着鼠标的移动而旋转,各个角度(这里处理的也不是很好,还希望看见的同志,能给些建议,大家一起交流一起进步)
还有拉近与放远,这里我觉得处理的还行,嘿嘿
点击一下空白部分,他又变回白色了
这是第一次写,写的不好,我会慢慢改进的。