前文:/Jaihk662/article/details/86749803(摄像机与Game视图)
后篇:/Jaihk662/article/details/88062565(解决摄像机跟随中的视野遮挡问题)
一、直接挂载
直接将摄像机作为主角的子物体
没了……
二、固定距离跟随方式
脚本如下:挂在摄像机上即可
using ;
using ;
using UnityEngine;
public class CameraMana : MonoBehaviour
{
Vector3 dir;
public GameObject myTank;
void Start()
{
//记录摄像机与物体的距离dir
dir = <Transform>().position - <Transform>().position;
}
void Update()
{
//保证dir不变
<Transform>().position = <Transform>().position - dir;
}
}
三、距离+方向跟随
(from, to, t):"from"和"to"以及API返回值都为向量,t为参数,用于返回差值向量 from+(to-from)*t
(Vector3):使游戏对象看向该坐标点(游戏对象的z轴指向Vector3)
using ;
using ;
using UnityEngine;
public class CameraFollow : MonoBehaviour
{
Vector3 aim;
public float m_Up = 10;
public float m_Forward = -10;
public float m_Speed = 10;
private Transform tankTran;
void Start()
{
tankTran = ("Tank").transform;// GetComponent<Transform>();
}
void LateUpdate()
{
aim = + * m_Up + * m_Forward;
= (, aim, m_Speed * );
(tankTran);
}
}
四、鼠标移动视角+摄像机跟随的一个简单实现
部分API:/Jaihk662/article/details/87643141
- (val, 10, 80):如果val<10或val>80返回10和80,否则返回val
- :摄像机的视野/聚焦,可以用来实现滚轮控制视野大小
- (Vector3 point, Vector3 axis, float angle):物体以point为中心绕着轴axis,旋转角度angle
注意:这个代码因为相机的跟随用的是插值运算,所以会导致相机跟角色有位置差,屏幕可能会出现抖动,如果出现这个问题就直接暴力赋值就ok了
using ;
using ;
using UnityEngine;
public class CameraMove : MonoBehaviour
{
Vector3 dis;
private int type;
public float myUp = 10;
public float myForward = -10;
public float mySpeed = 3;
private Transform playerTran, myTran;
void Start()
{
type = 1;
playerTran = ("player_archer_nerwin").transform;// GetComponent<Transform>();
myTran = <Transform>();
LookPlayer();
}
void Update()
{
if (() && ())
type ^= 1;
float left, up, forward;
if ((1)) //通过获得鼠标横纵轴移位,来控制摄像头视角移动,z轴保持不变
{
up = ("Mouse Y");
left = ("Mouse X");
(, , left * mySpeed);
if (( >= 2.5 || up < 0) && ( <= 7.5 || up > 0))
(, , -up * mySpeed);
dis = - ;
}
forward = ;
forward -= ("Mouse ScrollWheel") * 8;
forward = (forward, 10, 80);
= forward;
}
void LateUpdate()
{
if (("Vertical") != 0.0f || ("Horizontal") != 0.0f) //如果主角开始移动,则摄像机紧跟随,此时不能移动视角,只能控制聚焦
LookPlayerInPlay();
}
void LookPlayer()
{
= ;
+= * myUp;
+= * myForward;
(playerTran);
dis = - ;
}
void LookPlayerInPlay()
{
if (type == 0) //两种摄像机跟随方式
{
= + dis;
(playerTran);
}
else
{
= ;
+= * myUp;
+= * myForward;
(playerTran);
dis = - ;
}
}
}