unity中关于相机移动(包括平移和远近缩放)的三个脚本,如果使用的话将它们全部挂载在一个空object上就好,数值等可以参考下图:
代码:
CameraMoveDirectionKey.cs 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 using System.Collections;using System.Collections.Generic;using UnityEngine;public class CameraMoveDirectionKey : MonoBehaviour { public float moveSpeed = 100.0f ; public Transform camera; void Start ( ) { } void Update ( ) { float horizontalInput = Input.GetAxis("Horizontal" ); float verticalInput = Input.GetAxis("Vertical" ); Vector3 forwardMove = moveSpeed * camera.up * verticalInput * Time.deltaTime; forwardMove.y = 0 ; Vector3 rightMove = moveSpeed * camera.right * horizontalInput * Time.deltaTime; Vector3 move = forwardMove + rightMove; camera.position += move; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 using System.Collections;using System.Collections.Generic;using UnityEngine;public class CameraScroll : MonoBehaviour { public float zoomSpeed = 600.0f ; public Transform camera; void Start ( ) { } void Update ( ) { float scrollInput = -Input.GetAxis("Mouse ScrollWheel" ); Vector3 upMove = new Vector3(0 , scrollInput * zoomSpeed * Time.deltaTime, 0 ); camera.position += upMove; } }
CameraMoveMouse.cs 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 using System.Collections;using System.Collections.Generic;using UnityEngine;public class CameraMoveMouse : MonoBehaviour { public float mouseOffset=0.01f ; public Transform myCamera; public float moveSpeed=1f ; private float maxY = 1f ; private float maxX = 1f ; private void mouseInScreenBound ( ) { Vector3 v1 = Camera.main.ScreenToViewportPoint(Input.mousePosition); if (v1.y >= maxY - mouseOffset) { myCamera.Translate(Vector2.up * moveSpeed); } if (v1.y <= mouseOffset) { myCamera.Translate(Vector2.down * moveSpeed); } if (v1.x <= mouseOffset) { myCamera.Translate(Vector2.left * moveSpeed); } if (v1.x >= maxX - mouseOffset) { myCamera.Translate(Vector2.right * moveSpeed); } } private void Start ( ) { } private void Update ( ) { mouseInScreenBound(); } }