- Mathf的clamp
- lerp
- 代码实现跟随
- 方法二
clamp是Unity中限制轴向移动范围的函数
在游戏中,为了限制玩家的某一轴向的移动不超过一定的范围,我们可以用Mathf.Clamp来解决
Mathf.Clamp(float value,float min,float max)
在 Mathf.Clamp 中传入三个参数:value,min,max
限制 value的值在min,max之间,如果value大于max,则返回max,如果value小于min,则返回min,否者返回value;
lerppublic static Vector3 Lerp (Vector3 a, Vector3 b, float t);
参数
a 起始值,当 t = 0 时返回。
b 结束值,当 t = 1 时返回。
t 用于在 a 和 b 之间进行插值的值。
返回
Vector3 插值,等于 a + (b - a) * t。
描述
在两个点之间进行线性插值。
使用插值 t 在点 a 和 b 之间进行插值。参数 t 限制在范围 [0, 1] 内。这最常用于查找占两个终端之间距离特定百分比的点(例如,以便在这些点之间逐步移动对象)。
返回的值等于 a + (b - a) * t(也可以写作 a * (1-t) + b*t)。
当 t = 0 时,Vector3.Lerp(a, b, t) 返回 /a/。
当 t = 1 时,Vector3.Lerp(a, b, t) 返回 /b/。
当 t = 0.5 时,Vector3.Lerp(a, b, t) 返回 a 和 b 中间的点。
Transform.position = Vector3.Lerp(transform.position.x, targetPosition, Time.deltaTime);//能看起来像匀速移动代码实现跟随
首先创建一个C#脚本,接着创建一个空物体,并将脚本挂在空物体,且将相机作为其子物体。
其原理是将摄像机固定在一定范围,并且利用Lerp函数进行跟随目标移动
,拖拽需要跟随的目标,并且进行范围设定,此处范围限制可根据具体情况进行设定。如上即可代码实现摄像机跟随
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class camerafollow : MonoBehaviour
{
public Transform player;
//[SerializeField]
//public float smooth;
// Start is called before the first frame update
void Start()
{
player = GameObject.Find("knight").GetComponent();
}
// Update is called once per frame
void Update()
{
//写法一
transform.position = new Vector3(player.position.x, player.position.y, transform.position.z);
//写法二
//Vector2 camerafollow = player.position;
//transform.position = Vector2.Lerp(transform.position, camerafollow, smooth);
}
}
方法二
一(不推荐)
把摄像机挂在player下面(太low了)
二
在pack manger添加cinermachine;
之后在cineramachine添加2d摄像机,把player拖到VM vcam1即可



