Unity3D之2D游戏的背景补偿效果
public class BackgroundParallax : MonoBehaviour
{
public Transform[] backgrounds; //背景物体
public float parallaxScale; //摄像机移动偏移值的缩放系数
public float parallaxReductionFactor;//背景每一层补偿的系数
public float smoothing; //背景物体移动的平滑量
private Transform cam;//摄像机
private Vector3 previousCamPos;//摄像机上一针的位置
void Awake ()
{
cam = Camera.main.transform;
}
void Start ()
{
previousCamPos = cam.position;
}
void Update ()
{
//得到摄像机和上一帧的偏移值
float parallax = (previousCamPos.x - cam.position.x) * parallaxScale;
for(int i = 0; i < backgrounds.Length; i++)
{
//每一层的背景补偿运动的速度有不一样,I越大,补偿的速度也就越大
float backgroundTargetPosX = backgrounds[i].position.x + parallax * (i * parallaxReductionFactor + 1);
//Y轴方向不动
Vector3 backgroundTargetPos = new Vector3(backgroundTargetPosX, backgrounds[i].position.y, backgrounds[i].position.z);
//平滑的移动
backgrounds[i].position = Vector3.Lerp(backgrounds[i].position, backgroundTargetPos, smoothing * Time.deltaTime);
}
//更新上一帧摄像机的位置 previousCamPos = cam.position; } }