当前位置:网站首页>Unity parallax infinite scrolling background
Unity parallax infinite scrolling background
2022-07-05 04:52:00 【Im rime】
The parallax background actually moves with the camera , There is a certain difference between the background of each layer and the moving speed of the camera , It forms parallax . for example , The camera moved 5 grid , The first layer of background moves two spaces , The second layer of background moves one space , It forms parallax .
Post the code first :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ParallaxBackground : MonoBehaviour
{
private Transform mainCameraTransform;// The main camera's transform
private Vector3 lastCameraPosition;// Record the position of the main camera in the last frame
private float textureUnitSizeX;// Get the unit length of the background image in the project
public Vector2 bgMoveCoefficient;// The length coefficient of the background moving relative to the main camera
// Start is called before the first frame update
void Start()
{
mainCameraTransform = Camera.main.transform;// Get master camera transform
lastCameraPosition = mainCameraTransform.position;
Sprite sprite = GetComponent<SpriteRenderer>().sprite;
Texture2D texture = sprite.texture;
textureUnitSizeX = texture.width / sprite.pixelsPerUnit;// Calculate how many unit lengths the texture occupies
}
// Update is called once per frame
void Update()
{
}
private void LateUpdate()
{
Vector3 offsetPosition = mainCameraTransform.position - lastCameraPosition;
transform.position += new Vector3(offsetPosition.x * bgMoveCoefficient.x, offsetPosition.y * bgMoveCoefficient.y, transform.position.z);
lastCameraPosition = mainCameraTransform.position;
// If the main camera and the background image x Differ the width of the background image by one
if(Mathf.Abs(mainCameraTransform.position.x - transform.position.x) >= textureUnitSizeX)
{
float offsetPositionX = (mainCameraTransform.position.x - transform.position.x) % textureUnitSizeX;
transform.position = new Vector3(mainCameraTransform.position.x + offsetPositionX, transform.position.y, transform.position.z);
}
}
}
Parallax effect
1. First, you need to get the main camera transform, And record the main camera position, Later, we need to calculate how much the camera moves in each frame .
mainCameraTransform = Camera.main.transform;// Get master camera transform
lastCameraPosition = mainCameraTransform.position;
2. stay LateUpdate() Continuously calculate how much the main camera moves in each frame , And add this value to the position of the background ( remarks : It means how much the main camera moves , How much does the background image move ), You get the effect that the background moves with the main camera .
private void LateUpdate()
{
Vector3 offsetPosition = mainCameraTransform.position - lastCameraPosition;
transform.position += new Vector3(offsetPosition.x, offsetPosition.y, transform.position.z);
lastCameraPosition = mainCameraTransform.position;
}
3. Because the parallax is the length of each layer of background image moving is different , So let's change the above code a little
private void LateUpdate()
{
Vector3 offsetPosition = mainCameraTransform.position - lastCameraPosition;
transform.position += new Vector3(offsetPosition.x * bgMoveCoefficient.x, offsetPosition.y * bgMoveCoefficient.y, transform.position.z);
lastCameraPosition = mainCameraTransform.position;
}
there bgMoveCoefficient(Vector2 type ) It refers to the percentage of the value of the background movement relative to the value of the main camera movement , For example, you want the background to be x The axis moves slower than the main camera , Just put it x The value setting is less than 1.
4. Hang the script on each layer of background , And set up bgMoveCoefficient Value , You can get the parallax effect .
Infinite scrolling
1. Put each layer of background Draw Mode Set to Tiled
The purpose of setting this is to change the size of the texture , You can fill the blank part with texture content .
2. take Sprite The width of is increased to the size of three screens , Make sure the background doesn't see the boundary when it moves .
The infinite scrolling here is actually when the boundary of the background image is about to enter the range of the main camera , Change the position of the background image . So in the code , We need to calculate how many units of texture in the game scene .
Sprite sprite = GetComponent<SpriteRenderer>().sprite;
Texture2D texture = sprite.texture;
// because texture.width Is the actual pixel value of the picture , But in the game , A unit length may not be a pixel ( See how much you have set in the project )
// in other words position Move 1 Probably not only 1 Pixels , So we have to find out how many units the texture actually occupies in the project scene
// That is, the actual texture in the project scene width
textureUnitSizeX = texture.width / sprite.pixelsPerUnit;// Calculate how many unit lengths the texture occupies
2. In each frame, judge whether the boundary of the background image enters the range of the main camera , About to enter , Just reset the position of the background image
// If the main camera and the background image x Differ the width of the background image by one
// Because the front put the texture width The value is set to three times the size , When the main camera and the background image differ by one background image width , It indicates that the boundary is about to enter the shooting range of the main camera .
if(Mathf.Abs(mainCameraTransform.position.x - transform.position.x) >= textureUnitSizeX)
{
// Because it is possible that the difference between the background image and the main camera is not exactly the width of the background image , There may be some errors , So calculate the error here
float offsetPositionX = (mainCameraTransform.position.x - transform.position.x) % textureUnitSizeX;
// Reset the position of the background image
transform.position = new Vector3(mainCameraTransform.position.x + offsetPositionX, transform.position.y, transform.position.z);
}
You get the background image of infinite scrolling !
If there is any mistake or bad writing , Please give me some advice ! thank ! thank !
边栏推荐
- The principle of attention mechanism and its application in seq2seq (bahadanau attention)
- Create a pyGame window with a blue background
- 669. Prune binary search tree ●●
- Flutter 小技巧之 ListView 和 PageView 的各种花式嵌套
- [groovy] closure (closure call | closure default parameter it | code example)
- 2021 huashubei mathematical modeling idea + reference + paper
- AutoCAD - Center zoom
- Séparation et combinaison de la construction du système qualité
- [PCL self study: feature9] global aligned spatial distribution (GASD) descriptor (continuously updated)
- A survey of automatic speech recognition (ASR) research
猜你喜欢

【acwing】240. food chain

QT Bluetooth: a class for searching Bluetooth devices -- qbluetooth devicediscoveryagent

The 22nd Spring Festival Gala, an immersive stage for the yuan universe to shine into reality
![Private collection project practice sharing [Yugong series] February 2022 U3D full stack class 006 unity toolbar](/img/bf/fb4e85143d1461a2026c88cda4a18d.jpg)
Private collection project practice sharing [Yugong series] February 2022 U3D full stack class 006 unity toolbar

Looking at Chinese science and technology from the Winter Olympics: what is the mystery of the high-speed camera that the whole people thank?

The principle of attention mechanism and its application in seq2seq (bahadanau attention)

Qt蓝牙:搜索蓝牙设备的类——QBluetoothDeviceDiscoveryAgent

【Leetcode】1352. Product of the last K numbers
![[goweb development] Introduction to authentication modes based on cookies, sessions and JWT tokens](/img/20/5c5550e6dabc76702f0e7ce3bef068.jpg)
[goweb development] Introduction to authentication modes based on cookies, sessions and JWT tokens

Special information | finance, accounting, audit - 22.1.23
随机推荐
Introduction to JVM principle and process
2022 thinking of mathematical modeling a problem of American college students / analysis of 2022 American competition a problem
[groovy] closure (Introduction to closure class closure | closure parametertypes and maximumnumberofparameters member usage)
How to choose a panoramic camera that suits you?
中国艾草行业研究与投资前景预测报告(2022版)
介绍汉明距离及计算示例
"Measuring curve length" of CAD dream drawing
Research and investment forecast report of adamantane industry in China (2022 Edition)
[AI bulletin 20220211] the hard core up owner has built a lidar and detailed AI accelerator
中国AS树脂市场调研与投资预测报告(2022版)
[goweb development] Introduction to authentication modes based on cookies, sessions and JWT tokens
AutoCAD - isometric annotation
AutoCAD - Document Management
Setting up redis cluster cluster under Windows
Decryption function calculates "task state and lifecycle management" of asynchronous task capability
Stage experience
AutoCAD - continuous annotation
Rk3399 platform development series explanation (network debugging) 7.29 summary of network performance tools
[Business Research Report] top ten trends of science and technology and it in 2022 - with download link
Qt蓝牙:搜索蓝牙设备的类——QBluetoothDeviceDiscoveryAgent