视差背景
一、概述
多种实现方式可以参考:
2D视差背景实现的多种方式
二、脚本分析
1.相机移动 + Sprite移动
using System;
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
namespace BackgroundParallax_2.Scripts
{
/// <summary>
/// 背景视差
/// </summary>
public class ParallaxBackground : MonoBehaviour
{
[SerializeField] Vector2 parallaxEffectMultiplier;
/// <summary>
/// 当前相机位置
/// </summary>
private Transform cameraTransform;
/// <summary>
/// 上一次相机位置
/// </summary>
private Vector3 lastCameraPosition;
private float textureUnitSizeX;
private float textureUnitSizeY;
private void Start()
{
cameraTransform = Camera.main.transform;
lastCameraPosition = cameraTransform.position;
Sprite sprite = GetComponent<SpriteRenderer>().sprite;
Texture2D texture2D = sprite.texture;
textureUnitSizeX = texture2D.width / sprite.pixelsPerUnit;
textureUnitSizeY = texture2D.height / sprite.pixelsPerUnit;
Debug.Log(textureUnitSizeX);
}
/// <summary>
/// LateUpdate是晚于所有Update执行的,此处用于将背景移动到
/// </summary>
private void LateUpdate()
{
Vector3 deltaMovement = cameraTransform.position - lastCameraPosition;
//设置一个值,此时相机移动,背景不会完全跟随
transform.position += new Vector3(deltaMovement.x * parallaxEffectMultiplier.x, deltaMovement.y * parallaxEffectMultiplier.y, deltaMovement.z);
lastCameraPosition = cameraTransform.position;
//当相机的坐标超过纹理的边界时,同时为了不发生拼接感,建议spriterender的size扩展到view的三倍,这样左右移动都不会有拼接感
//原理就是uv重复,到一个纹理结束时,加上或减去纹理场长宽还是会回到相同纹理坐标
if (Mathf.Abs(cameraTransform.position.x - transform.position.x) >= textureUnitSizeX)
{
float offsetPositionX = (cameraTransform.position.x - transform.position.x) % textureUnitSizeX;
transform.position = new Vector3(cameraTransform.position.x + offsetPositionX, transform.position.y,transform.position.z);
}
if (Mathf.Abs(cameraTransform.position.y - transform.position.y) >= textureUnitSizeY)
{
float offsetPositionY = (cameraTransform.position.y - transform.position.y) % textureUnitSizeX;
transform.position = new Vector3(cameraTransform.position.x , transform.position.y + offsetPositionY,transform.position.z);
}
}
}
}
2.UV移动
直接写shader,但是实现复杂效果不方便