Unity相机视野控制与相机旋转

    技术2022-07-10  114

    射线检测物体并拖拽物体

    using UnityEngine; public class RaycastTest : MonoBehaviour { private bool isRay=true; Vector3 offset; Vector3 screenTarget; GameObject targetGameObject;//射线碰撞的物体 RaycastHit hit; public LayerMask clickableLayer;//屏幕射线可碰撞的层 void Update() { DragObject(); } private void DragObject() { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); //Debug.DrawLine(ray.origin, Input.mousePosition, Color.red, 5f);//绘制射线,只能在Scene场景下看到 if (Input.GetMouseButton(0)) { if (isRay)//鼠标一直按下,拖拽物体时只能发射一次射线,进行一次射线检测 { //Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); if (Physics.Raycast(ray,out hit,100f,clickableLayer.value)) { Debug.DrawLine(ray.origin, hit.point, Color.red, 5f);//绘制射线,只能在Scene场景下看到 targetGameObject = hit.collider.gameObject;//返回射线碰撞到的物体 //将射线碰撞到的物体从世界坐标转为屏幕坐标 screenTarget = Camera.main.WorldToScreenPoint(targetGameObject.transform.position); offset = targetGameObject.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x,Input.mousePosition.y,screenTarget.z)); } isRay = false;//射线检测一次后不能再次检测 } if (!isRay)//拖拽物体 { Vector3 currentScreenSpace = new Vector3(Input.mousePosition.x,Input.mousePosition.y,screenTarget.z); Vector3 currentPosition = Camera.main.ScreenToWorldPoint(currentScreenSpace)+offset; targetGameObject.transform.position = currentPosition; } } if (Input.GetMouseButtonUp(0))//鼠标抬起,下次点击鼠标可以再次进行射线检测 { isRay = true; } } }

    相机移动与旋转

    using UnityEngine; public class ViewChange1 : MonoBehaviour { void Update() { ScaleView(); CameraMove(); RotateCamera(); } //鼠标滚轮改变相机视野大小 private void ScaleView() { if (Input.GetAxis("Mouse ScrollWheel") > 0) //向上按滚轮,视野变小,物体变大 { transform.GetComponent<Camera>().fieldOfView -= 2; } else if (Input.GetAxis("Mouse ScrollWheel") < 0) { transform.GetComponent<Camera>().fieldOfView += 2; } } //W、A、S、D移动相机 private void CameraMove() { float h = Input.GetAxisRaw("Horizontal1"); transform.Translate(Vector3 .right * h * 0.5f, Space.Self); float v = Input.GetAxisRaw("Vertical1"); transform.Translate(Vector3.forward * v * 0.5f, Space.Self); } private void RotateCamera() { if (Input .GetMouseButton (1)) { transform.Rotate(Vector3.up * Input.GetAxisRaw("MouseX") * 0.05f, Space.World); //transform.Rotate(-Vector3.right * Input.GetAxisRaw("MouseY") * 0.05f, Space.World); } } }
    Processed: 0.014, SQL: 9