Unity2D横板游戏之背景视差与无限滚动效果
简单介绍
背景视差效果。在 2D 横板游戏中,由若干个背景图片构成的背景,在背景移动的过程中,每一个背景图片的移动速度均不同,靠近玩家的背景图片移动速度快,而远离玩家的背景图片移动速度慢,从而形成背景的视差效果,使背景更加立体且富有层级。
背景无限滚动效果。背景无限滚动并不是在游戏场景中加载无限的背景,而是在水平方向上使用两个紧密相邻的背景进行交替渲染,从而形成无限滚动的错觉。
代码设计
public class BackgroundEffect : MonoBehaviour
{
private Transform _follow;
private GameObject _background1;
private GameObject _background2;
private float _backgroundWidth;
private float _moveSpeed;
private Vector2 _previousCameraPosition;
public void Initialize(Transform follow, GameObject background1, GameObject background2, float moveSpeed)
{
_follow = follow;
_background1 = background1;
_background2 = background2;
_moveSpeed = moveSpeed;
_previousCameraPosition = _follow.position;
SpriteRenderer spriteRenderer = _background1.GetComponent<SpriteRenderer>();
if (spriteRenderer == null)
{
return;
}
Sprite sprite = spriteRenderer.sprite;
Vector3 localScale = _background1.transform.localScale;
_backgroundWidth = sprite.bounds.size.x * localScale.x;
Vector3 background2Position = _background2.transform.position;
background2Position = new Vector2(background2Position.x - _backgroundWidth, background2Position.y);
_background2.transform.position = background2Position;
}
private void FixedUpdate()
{
Vector2 currentCameraPosition = _follow.position;
Vector2 cameraOffset = currentCameraPosition - _previousCameraPosition;
Vector3 backgroundPosition = _background1.transform.position;
backgroundPosition = new Vector2(backgroundPosition.x + cameraOffset.x - cameraOffset.x * _moveSpeed, backgroundPosition.y + cameraOffset.y);
_background1.transform.position = backgroundPosition;
backgroundPosition = _background2.transform.position;
backgroundPosition = new Vector2(backgroundPosition.x + cameraOffset.x - cameraOffset.x * _moveSpeed, backgroundPosition.y + cameraOffset.y);
_background2.transform.position = backgroundPosition;
if (_background1.transform.position.x <= _follow.position.x)
{
Vector3 background2Position = _background2.transform.position;
background2Position = new Vector2(background2Position.x + 2f * _backgroundWidth, background2Position.y);
_background2.transform.position = background2Position;
(_background1, _background2) = (_background2, _background1);
}
if (_follow.position.x <= _background2.transform.position.x)
{
Vector3 background1Position = _background1.transform.position;
background1Position = new Vector2(background1Position.x - 2f * _backgroundWidth, background1Position.y);
_background1.transform.position = background1Position;
(_background1, _background2) = (_background2, _background1);
}
_previousCameraPosition = currentCameraPosition;
}
}
后记
由于个人能力有限,文中不免存在疏漏之处,恳求大家斧正,一起交流,共同进步。
标签:横板,transform,Unity2D,background2,background1,backgroundPosition,private,position From: https://www.cnblogs.com/kkelin/p/18169450