码迷,mamicode.com
首页 > 移动开发 > 详细

unity2D背景移动补偿从而获得3d错觉效果

时间:2018-11-22 00:05:16      阅读:509      评论:0      收藏:0      [点我收藏+]

标签:gen   vat   col   sys   led   length   called   private   back   

2d平台跳跃游戏当相机移动的时候背景跟随进行微调移动,从而使得玩家获得3d的错觉

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BackGroundParallax : MonoBehaviour {

public Transform[] backgrounds;//所有的背景层,这里,离玩家最近的背景的下标i最小,当i足够大时,背景和相机是一起位移的,比如真实世界里,人走动的时候,周围的房屋都向后移动,而天空中的星星却看起来没有移动过
public float parallaxScale;//相对相机的移动补偿的比例值
public float parallaxScaleReductionFactor;//对于不同的背景层的移动补偿的差值比例
public float smoothing;

private Transform cam;
private Vector3 previousCamPos;//相机在上一帧的位置

// Use this for initialization
void Start () {
cam = Camera.main.transform;
previousCamPos = cam.position;
}

// Update is called once per frame
void Update () {
float parallax = (previousCamPos.x - cam.position.x) * parallaxScale;//根据相机的单帧位移获得补偿值大小

for (int i = 0; i < backgrounds.Length; i++) {
//获得位移的x值,i*parallaxScaleReductionFactor得到不同背景层的补偿差
float backgroundTargetPosX = backgrounds[i].position.x + parallax * (i*parallaxScaleReductionFactor+1);

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;
}
}

unity2D背景移动补偿从而获得3d错觉效果

标签:gen   vat   col   sys   led   length   called   private   back   

原文地址:https://www.cnblogs.com/xiaoahui/p/9998165.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!