当前位置:网站首页>Unity3d C#利用材质(Material)贴图的偏移实现2D游戏单背景图无限移动背景效果功能(含源码)
Unity3d C#利用材质(Material)贴图的偏移实现2D游戏单背景图无限移动背景效果功能(含源码)
2022-04-21 20:38:00 【十幺卜入】
前言
2D的游戏背景基本是一张图,前后可以无缝拼接的那种,无限的背景滚动的效果,可以通过多张的图拼接起来,随着相机移动动态的创建/移位背景图可以实现,不过,本文介绍的方法是使用单张Sprite实现,具体实现就是通过脚本设置贴图的Offset来实现。
效果

实现
搭建节点
场景如图:

只有单个背景图(Sprite Renderer)。需要放到相机节点下。
贴图修改
选中贴图BG,在Inspector窗口修改 Type 和Wrap Mode:

Repeat重复的话,就可以实现无限移动的效果。
制作材质
在Assets窗口右键 Create 》 Material。
创建有重命名一下,再将着色器选为Unlit/Texture,如果是透明通道的贴图,选择Unlit/Transparent。
最后将贴图关联一下即可:

关联节点
最后在Sprite Renderer上关联 贴图和材质。

编码
编写代码:
using UnityEngine;
public class SrollWithCam : MonoBehaviour
{
public Transform camTran;
public Material mat;
public float OffsetRat = 0.01f;
void Start()
{
if (camTran == null)
camTran = transform.parent;
}
private void FixedUpdate()
{
if (camTran != null) {
mat.SetTextureOffset("_MainTex", new Vector2(camTran.transform.position.x * OffsetRat, 0));
}
}
}
根据相机的位置修改材质的偏移值即可。
版权声明
本文为[十幺卜入]所创,转载请带上原文链接,感谢
https://blog.csdn.net/qq_33789001/article/details/124327102
边栏推荐
猜你喜欢

< 2021SC@SDUSC > Introduction to the jpress group on software engineering application and practice of Shandong University

《动手学机器人学》7.2.3姿态的多种表示,四元数,欧拉角旋转矩阵、轴角ROS2

Specific methods of configuring Profibus and PROFINET communication in two TIA botu projects

Debugging MS source code
![[high concurrency] analysis of thread pool and ThreadPoolExecutor class](/img/9c/ccd119193ffb9b82bf08cedb38fd0b.jpg)
[high concurrency] analysis of thread pool and ThreadPoolExecutor class

In depth analysis of TCP three handshakes, the interviewer applauded

2022-4-11至2022-4-17周报
![[network security] stapler1 of red team penetration project (Part 2)](/img/39/7d5594da6e7e89e510040b66eef383.png)
[network security] stapler1 of red team penetration project (Part 2)

Actual combat | performance pressure test of JMeter typical e-commerce scenario (order / payment)

C语言题目一:1,2,3,4能组成的三位数
随机推荐
Why do you have no idea when doing data analysis?
Circular linked list of single and double linked lists (XV)
如何用Sonic云真机打王者
(转载)MySQL读写分离--集群和高并发
6、Qt使用MySQL例子
Debugging MS source code
《ROS2机器人建模URDF》8.1URDF统一机器人建模语言
Yaml
【Daily LeetCoding Challenge14】 K 个一组翻转链表
CUDA02 - 访存优化和Unified Memory
分布式秒杀系统构建
Pytorch框架 || torch.nn.modules.Module(nn.Module)
After five years of outsourcing, I'm almost a loser
关于c34d
C# 双保险进程监视器 lol 保证被监视的程序'几乎'永远运行. 关键字:进程操作 进程查看 创建进程
《ROS2机器人建模URDF》8.2RVIZ2可视化移动机器人模型
TCP example of grpc implemented by golang
C语言题目一:1,2,3,4能组成的三位数
动态规划小结
824.山羊拉丁文