前言
开发游戏经常需要用到把前景、场景、背景等不同层级的物体进行不同速度的移动以实现真实感。
效果云、建筑、地面、前景植被各层次场景分层移动。
using UnityEngine;
public class DistantView : MonoBehaviour
{
public GameObject follow;
public float scaleOffset;
public bool isHorizontal = true;
public bool isVertical = true;
Vector2 pos;
Vector2 followPos;
float offsetX;
float offsetY;
private void Start()
{
if (follow != null)
followPos = follow.transform.localPosition;
}
void LateUpdate()
{
if (follow!=null)
{
pos = transform.localPosition;
if (isHorizontal)
{
offsetX = (follow.transform.localPosition.x - followPos.x) * scaleOffset;
pos.x += offsetX;
}
if (isVertical)
{
offsetY = (follow.transform.localPosition.y - followPos.y) * scaleOffset;
pos.y += offsetY;
}
transform.localPosition = pos;
followPos = follow.transform.localPosition;
}
}
}
用法
将不同层级的物体放入不同的父物体下分别管理。 给每个父物体挂上脚本。
Follow为跟随的基准对象。(比如玩家,相机等) ScaleOffset为移动速率,1为和目标移速一致,越小越慢,越大越快。0为不移动,负值为反向移动。(前景可能要用到负值) Hor和Ver为跟随哪个轴。