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;
}
}
後記
由於個人能力有限,文中不免存在疏漏之處,懇求大家斧正,一起交流,共同進步。