0%

unity中关于相机移动的脚本

unity中关于相机移动(包括平移和远近缩放)的三个脚本,如果使用的话将它们全部挂载在一个空object上就好,数值等可以参考下图:
1

代码:

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;


/// <summary>
/// 镜头移动方式1:通过wasd(或者上下左右方向键)来上下左右平移镜头
/// </summary>
public class CameraMoveDirectionKey : MonoBehaviour
{
//镜头平移的速率
public float moveSpeed = 100.0f;

//镜头
public Transform camera;





// Start is called before the first frame update
void Start()
{

}

// Update is called once per frame
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;

}
}

CameraScroll.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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;



/// <summary>
/// 滑动鼠标滚轮使得镜头竖直上下移动
/// </summary>
public class CameraScroll : MonoBehaviour
{
public float zoomSpeed = 600.0f;

public Transform camera;


// Start is called before the first frame update
void Start()
{

}

// Update is called once per frame
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;

/// <summary>
/// 鼠标移动到屏幕边缘然后使得镜头移动
/// </summary>
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();
}

}