实用系列(一) 简单的镜头跟随
功能介绍:
- 令相机跟随游戏物体;
- 按下Q,E可以左右旋转视角;
- 滚动鼠标滑轮可以放大或者缩小视角;
代码使用方法:
- 新建C#脚本FollowPlayer并挂载相机上,设置跟随物体的Tag值为Player;
- 调整当前Scene视角对准跟随物体,按下Ctrl + Shift + F(即Align With View),让相机视角对准跟随物体,设置好相关参数;
- 运行场景,相机即可跟随游戏物体移动
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FollowPlayer : MonoBehaviour {
private Transform player; // 跟随对象的初始位置
private Vector3 offsetPosition; // 相机与对象的位置偏移
private bool isRotating = false; // 是否旋转
public float distance = 0;
public float scrollSpeed = 3; // 拉进/拉远视角的速度
public float rotateSpeed = 2; // 旋转速度
void Start () {
player = GameObject.FindGameObjectWithTag(Tags.player).transform; // 获取跟随物体的位置
transform.LookAt(player.position);
offsetPosition = transform.position - player.position;
}
void Update () {
transform.position = offsetPosition + player.position;
RotateView(); // 处理视野的旋转
ScrollView(); // 处理视野的拉近和拉远效果
}
void ScrollView() {
// 向后滑动返回负值(拉远视野) 向前滑动返回正值(拉近视野)
distance = offsetPosition.magnitude;
distance -= Input.GetAxis("Mouse ScrollWheel") * scrollSpeed;
distance = Mathf.Clamp(distance, 5, 10);
offsetPosition = offsetPosition.normalized * distance;
}
void RotateView() {
if (Input.GetKey(KeyCode.Q) || Input.GetKey(KeyCode.E)) {
isRotating = true;
}
else {
isRotating = false;
}
if (isRotating && Input.GetKey(KeyCode.Q)) {
transform.RotateAround(player.position, Vector3.up, -rotateSpeed);
}
else if (isRotating && Input.GetKey(KeyCode.E)) {
transform.RotateAround(player.position, Vector3.up, rotateSpeed);
}
offsetPosition = transform.position - player.position;
}
}
Tags:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Tags : MonoBehaviour {
public static string player = "Player"; // 本人习惯如此保存所有的tag值
}
缺点:
- 每次手动更改游戏对象位置后,必须重新指定跟随视角(Ctrl + Shift + F)
- 若要Destroy跟随对象,需关闭此脚本,否则会报错