最近在一个3D汽车虚拟展示的项目,将其中的汽车开门关门的脚本简单的介绍一下吧,主要的原理就是通过从摄像机发射一个到屏幕点击的位置的一个射线,然后判断这个射线是否碰到你想要碰到的位置,如果碰到则实现逻辑过程。旋转缩放就是将摄像机围绕着汽车为轴心进行旋转,缩放就是改变摄像机的视角范围,原理就是这么简单,接着上代码:
1.开关车门:
using UnityEngine; using System.Collections; public class opendoor : MonoBehaviour { private bool isOpenDoor = false; private bool openDoor = false; private bool closeDoor = false; private int target = 0; int flag = 0; Ray ray; RaycastHit hitobj; private GameObject doorl; // Use this for initialization void Start () { doorl = GameObject.Find("doorL"); } // Update is called once per frame void Update () { //画出射线 ray = Camera.main.ScreenPointToRay(Input.mousePosition); if (Input.GetMouseButtonDown(0)) { //鼠标点击车门 if (Physics.Raycast(ray,out hitobj,1000)) { print("ddd"); Debug.DrawLine(ray.origin, hitobj.point); if (hitobj.collider.name == "doorL") { print("111"); if (flag == 0) { openDoor = true; closeDoor = false; } else { closeDoor = true; openDoor = false; } flag++; flag %= 2; } } } if (openDoor) { //开门 if (target < 40 && !isOpenDoor) { doorl.transform.Rotate(Vector3.forward, 1); target = target + 1; } else { isOpenDoor = true; } } if(closeDoor) { //关门 if (isOpenDoor && target > 0) { doorl.transform.Rotate(-Vector3.forward, 1); target -= 1; } else { isOpenDoor = false; } } } }
将以上代码添加到car模型上,然后点击鼠标实现开门和关门的一个简单效果,效果截图:
鼠标左键点击车门:
2.旋转缩放:
//旋转 if (Input.GetMouseButtonDown(0)) { p1 = new Vector2(Input.mousePosition.x, Input.mousePosition.y);//鼠标右键按下时记录鼠标位置p1 } if (Input.GetMouseButton(0)) { p2 = new Vector2(Input.mousePosition.x, Input.mousePosition.y);//鼠标右键拖动时记录鼠标位置p2 //下面开始旋转,仅在水平方向上进行旋转 float dx = p2.x - p1.x; float dy = (float)0.1*(p2.y - p1.y); transform.RotateAround(car.transform.position, Vector3.up, dx * Time.deltaTime); //鼠标上下移动 //transform.Translate(dy*Vector3.up * Time.deltaTime); light.transform.RotateAround(car.transform.position, Vector3.up, dx*Time.deltaTime); } //鼠标滚轮控制场景大小 // 如果按住滑轮 if (Input.GetAxis("Mouse ScrollWheel") > 0) { Debug.Log(1); Debug.Log(Input.GetAxis("Mouse ScrollWheel")); if (normalDistance >= MouseZoomMin && normalDistance <= MouseZoomMax) { normalDistance -= Input.GetAxis("Mouse ScrollWheel") * MouseWheelSensitivity; } if (normalDistance < MouseZoomMin) { normalDistance = MouseZoomMin; } if (normalDistance > MouseZoomMax) { normalDistance = MouseZoomMax; } transform.camera.fieldOfView = normalDistance; } //后滚 else if (Input.GetAxis("Mouse ScrollWheel") < 0) { Debug.Log(-1); if (normalDistance >= MouseZoomMin && normalDistance <= MouseZoomMax) { normalDistance -= Input.GetAxis("Mouse ScrollWheel") * MouseWheelSensitivity; } if (normalDistance < MouseZoomMin) { normalDistance = MouseZoomMin; } if (normalDistance > MouseZoomMax) { normalDistance = MouseZoomMax; } // transform.Translate(-transform.forward * normalDistance); transform.camera.fieldOfView = normalDistance; }
效果图:
关于Unity3D,我们有个专门技术讨论的大群,可以进行技术交流和咨询,群号:858550
欢迎进行技术讨论,里面有不少大牛
时间: 2024-10-28 17:35:54