当前位置:网站首页>[unity3d] rolling barrage effect in live broadcasting room
[unity3d] rolling barrage effect in live broadcasting room
2022-04-23 02:38:00 【Ben Boli】
There will always be new products in the new era , For example, live broadcast . The feature of live broadcast is real-time interaction . Chat the original video one-on-one , Become a one to many chat between the anchor and the comment area . The characteristics of live broadcast are also obvious , The bottom camera renders a real-time picture ; Real time comments are displayed on the left corner of the screen , Click like to buy in the lower right corner , Clicking the screen at the same time will trigger the like animation ; The top left corner is the avatar, the number of fans and attention , Then follow a row of reward charts . If these apply to the game , Is to take the real-time picture of the original camera , Just turn it into a game scene .
The following mainly introduces the realization of single machine live broadcast barrage and the special effects of gift giving .
Interface UI build
Create a canvas
And set it to screen overlay . stay CanvasScaler Set in the UI The zoom mode is screen size , The reference resolution is temporarily set to 750*1334.
Create a ScrollView The scroll area is at the bottom
The layout is adjusted as follows :
Then delete the horizontal and vertical scroll bars .
Choose Viewport node , Modify its layout , And remove the original default Mask, Replace with a rectangular mask Rect Mask 2D, Temporary settings softness by 30, You can modify it later .
Content Also modify the layout , Then add the vertical component Vertival Layout Group, Child alignment is MiddleLeft, Center left align .
Add another component that adapts to the height Content Size Fitter, The vertical direction is set to :Preferred Size, In this way content If you add child nodes, they can also change their size .
Create a single bullet screen UI style
First , Find a rounded bullet screen UI Background map itemBg.png, And then in content Add under node Image picture , Name it BarrageItem, And will itemBg Assign a value to Image. Image type select slice , Cut out both ends in the image editor , In this way, when changing the size of the picture, the two ends will not be stretched to .
Add horizontal layout Horizontal Layout Group, And size adaptation components Content Size Fitter. The setting is as shown in the figure :
stay BarrageItem Next, add two Text, Used to fill in the name of netizens NameText And barrage content DescText. After adjusting the font size and color , The same plus size fits .
here , The barrage effect is like this :
adjustment BarrageItem Of layout Configuration of components :
Click on BarrageItem,ctrl+D Copy one more BarrageItem, Look at the list UI What does it look like :
Very compact and against the left side of the outer container , So we need to set their parent nodes content Of Layout Adjustment :
Will the barrage BarrageItem Drag alone to Prefabs As a preform , Then remove it from the parent node Content remove , Then roll the barrage ScrollView Also drag it into the resource as a prefab .
thus , bullet chat UI The construction can come to an end .
Data editing
One 、 Nickname data
Nickname data structure UserName
There is one int Type of id And a string Nickname of type
public struct UserName{
int id;
public string nickName;
}
establish JSON
Can pass unity The plug-in will directly excel The file is assigned to unity Nodes in the to convert files , You can also use other plug-ins to excel File conversion to Json file , Put it into the project for unity call .
The latter is used here :
Good configuration excel After using the tool to convert json as follows , Put it in the Assets\Resources\Jsons\ in :
Establish data management module
When the class is initialized Json Convert to object . Write another one. GetRandomName Method is called to get a random nickname .
public class UserNameClass{
static public UserName[] userName;// To configure
public UserNameClass(){
LoadByJson();
}
private void LoadByJson () {
TextAsset text = Resources.Load<TextAsset>("Jsons/" + "UserName");
userName = JsonMapper.ToObject<UserName[]>(text.text);
}
static public UserName GetRandomName(){
return userName[Random.Range(0, userName.Length)];
}
}
Two 、 Barrage data
First , The application of barrage in the game is divided into the following categories :
- Ordinary barrage , Simulated players speak , A random ;
- Guidance barrage , Simulate task guidance through player dialogue , Multiple barrages appear in sequence ;
- Specific scene barrage , Simulate triggering multiple barrage contents under special circumstances , Multiple barrages appear randomly out of order ;
- Reward barrage , Simulated player reward , Random insertion appears , With data addition and gift animation ;( This will not be realized in this article )
thus , The barrage will be divided into the following three types , The structure is id,desc( Description of barrage type , For auxiliary meter )
The structure of each Barrage is index( Serial number ),desc( The contents of the barrage )
The numbers in the first column correspond to the above id,index Corresponding to No id The third group of barrage index Shrapnel , That is, if only 0 The representative is actually a single barrage . The bullet screen content can be filled in by yourself .
To Json after , Three types of barrage structures are like this :
Paragraph barrage , Pictured , Every id There is only one in the .
Ordinary barrage , Pictured , Every id There is only one in the .
Specific scene barrage , In fact, it is the same as the paragraph bullet screen with guiding function , Similarly, this json Files in Resoutces/Jsons in :
Next , Save the three types of barrage into their respective categories , And set their individual scrolling speed :
item_arr It contains the above 【 Barrage combination 】 Corresponding id; The upper and lower limits of the rolling speed of the barrage are set . Convert to Barrage.json Put the file in the same place as above Resources/Jsons In the document ;
Establish data management module
According to the above json Create three classes for subsequent calls :
/// <summary>
/// Summary of barrage types
/// </summary>
public class BarrageJson
{
public int id = 0;
public string type = "";
public double min;// Screen rolling speed
public double max;// Screen rolling speed
public string[] item_arr;// bullet chat id
}
/// <summary>
/// Barrage combination
/// </summary>
public class BarrageItemsJson
{
public int id;
public string desc;// Type specification
public BarrageItemJson[] item;
}
/// <summary>
/// Single case of barrage
/// </summary>
public class BarrageItemJson
{
public int index;//
public string desc;// The contents of the barrage
}
And then create a BarrageClass class , And carry on json And the initialization of the above class :
using System.Collections.Generic;
using UnityEngine;
using LitJson;
public class BarrageClass{
public static BarrageClass instance;
BarrageJson[] barrageJson;// To configure
BarrageItemsJson[] barrageItemsJson;// To configure
private List<BarrageItemJson> curbarrages = new List<BarrageItemJson>();
static public Dictionary<BarrageType, List<BarrageItemsJson>> TYPE_Barrage = new Dictionary<BarrageType, List<BarrageItemsJson>>{
};
public BarrageClass()
{
if(instance != null){
return;
}
instance = this;
LoadByJson();
reset();
}
public void reset()
{
TYPE_Barrage.Add(BarrageType.newbie, getBarrageListByType(BarrageType.newbie));
TYPE_Barrage.Add(BarrageType.day, getBarrageListByType(BarrageType.day));
TYPE_Barrage.Add(BarrageType.night, getBarrageListByType(BarrageType.night));
TYPE_Barrage.Add(BarrageType.success, getBarrageListByType(BarrageType.success));
TYPE_Barrage.Add(BarrageType.fail, getBarrageListByType(BarrageType.fail));
Debug.Log(" Novice barrage :"+JsonMapper.ToJson(TYPE_Barrage[BarrageType.newbie]));
}
// Get barrage combination ;
public List<BarrageItemsJson> getBarrageListByType(BarrageType type){
string[] idArr = barrageJson[((int)type)].item_arr;
List<BarrageItemsJson> barrageArr = new List<BarrageItemsJson>();
for(int i = 0; i < idArr.Length; i++) {
int id = int.Parse(idArr[i]);
barrageArr.Add(barrageItemsJson[id]);
}
return barrageArr;
}
//Json Convert to corresponding object
private void LoadByJson () {
TextAsset text = Resources.Load<TextAsset>("Jsons/" + "Barrage");
barrageJson = JsonMapper.ToObject<BarrageJson[]>(text.text);
Debug.Log(" bullet chat : primary json"+text);
text = Resources.Load<TextAsset>("Jsons/" + "BarrageItem");
barrageItemsJson = JsonMapper.ToObject<BarrageItemsJson[]>(text.text);
Debug.Log(" bullet chat :"+JsonMapper.ToJson(barrageJson) + JsonMapper.ToJson(barrageItemsJson));
}
}
Write the barrage combination type as enum Easy to understand :
public enum BarrageType{
newbie,
day,
night,
success,
fail
}
By combining types , To get [ Barrage combination ] The way to assemble :getBarrageByType(BarrageType type)
// Get barrage type ;
public BarrageJson getBarrageByType(BarrageType type){
return barrageJson[((int)type)];
}
adopt [ Barrage combination ] Of id, To get this [ Barrage combination ] Multiple barrages in the collection item Methods :getBarrageByID(BarrageType id)
// Get barrage combination ;
public BarrageItemJson[] getBarrageByID(int id){
return barrageItemsJson[id].item;
}
adopt getBarrageByType and getBarrageByID Method to set the dictionary , You can get it directly from the dictionary [ Barrage combination ] aggregate :
// Get barrage combination ;
public List<BarrageItemsJson> getBarrageListByType(BarrageType type){
string[] idArr = getBarrageByType(type).item_arr;
List<BarrageItemsJson> barrageArr = new List<BarrageItemsJson>();
for(int i = 0; i < idArr.Length; i++) {
int id = int.Parse(idArr[i]);
barrageArr.Add(barrageItemsJson[id]);
}
return barrageArr;
}
3、 ... and 、 Barrage display and call
Bullet screen rolling area
The first is the rolling area of the barrage , establish BarrageUI Script , Make a simple assignment .
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class BarrageUI : MonoBehaviour
{
public ScrollRect scroll_rect;// Scroll area
public ScrollViewNevigation scrollViewNevigation;// Plug in for scroll jog animation
public GameObject item;// bullet chat object
private List<BarrageItemsJson> barrageItemsJson = new List<BarrageItemsJson>();// Barrage combination list
private BarrageItemsJson curBarrageArr;// The current barrage
private BarrageType barrageType;// Current barrage combination type
private BarrageItemJson curBarrage;// Current barrage
private int arrIndex = 0;// Which group of barrages
private int index = 0;// What is the first bullet screen in the bullet screen combination
private BarrageClass barrageClass;// Current barrage information
BarrageItemJson[] baragesArr;
double min;// Minimum screen speed
double max;// Maximum barrage speed
bool isStop = true;// Whether the barrage rolling has stopped
void Start(){
// MessageCenter.Instance.RigisterListener(MessageName.INSERT_BARRAGE, InsertBarrage);
barrageClass = BarrageClass.instance;
}
}
Hang up Barrage In the preform , Then add ScrollViewNevigation Script , And the assignment :
Set the barrage list SetBarrageList, Initialize the appearance time of the barrage . If the automatic play of the barrage stops , You need to call NextBarrageArr Start it up
public void SetBarrageList(BarrageType type) {
barrageType = type;
min = barrageClass.getBarrageByType(type).min;
max = barrageClass.getBarrageByType(type).max;
barrageItemsJson = BarrageClass.TYPE_Barrage[barrageType];
index = 0;
arrIndex = 0;
if(isStop){
NextBarrageArr();
}
}
Set the next set of barrages NextBarrageArr:
// Next set of bullet screen paragraphs
public void NextBarrageArr(){
isStop = false;
if(barrageType == BarrageType.newbie){
if(TaskClass.instance.isNewbie){
// The novice stage is not over
arrIndex = TaskClass.instance.newbieID;// Play the next novice bullet screen
curBarrageArr = barrageItemsJson[arrIndex];
baragesArr = curBarrageArr.item;
StartCoroutine(nextBarrage());
}else{
// The novice phase is over
isStop = true;
SetBarrageList(BarrageType.day);
}
}else if(barrageType == BarrageType.day || barrageType == BarrageType.night){
// Draw a piece of barrage at random
arrIndex = Random.Range(0, barrageItemsJson.Count);
curBarrageArr = barrageItemsJson[arrIndex];
baragesArr = curBarrageArr.item;
index = 0;
StartCoroutine(nextBarrage());
}else if(barrageType == BarrageType.success || barrageType == BarrageType.fail){
// Bullet screen under specific scenes
if(arrIndex < barrageItemsJson.Count){
// Play the bullet screen of successful and failed paragraphs in turn
curBarrageArr = barrageItemsJson[0];
baragesArr = curBarrageArr.item;
baragesArr = AddBarage();
RandomList(baragesArr, curBarrageArr.item.Length, out baragesArr);// Disrupt the order of each barrage
StartCoroutine(nextBarrage());
arrIndex ++;
}
}
}
void RandomList(BarrageItemJson[] barrageItemsArr, int count, out BarrageItemJson[] rangeArr{
List<BarrageItemJson> barrageList = new List<BarrageItemJson>();
List<int> indexList = new List<int>();// One and animalList The same number of sequences List
for(int i = 0; i < barrageItemsArr.Length; i++) {
indexList.Add(i);
}
int countNum = barrageItemsArr.Length;
while (barrageList.Count < countNum)
{
int rangeNum = Random.Range(0,indexList.Count-1);// A random number
int index = indexList[rangeNum];// stay List Take out the of the random number index
barrageList.Add(barrageItemsArr[index]);
indexList.Remove(index);
if(barrageList.Count == count) break;
}
rangeArr = barrageList.ToArray();
}
Set the next barrage nextBarrage
// The next barrage
IEnumerator nextBarrage(){
curBarrage = baragesArr[index];
StartCoroutine(createItem());
index ++;
yield return new WaitForSeconds(Random.Range(((float)min), ((float)max)));
if(barrageType == BarrageType.newbie){
// After the novice Barrage is played, there will be no new content
if(index < baragesArr.Length){
StartCoroutine(nextBarrage());
}else{
isStop = true;
}
}else if(barrageType == BarrageType.day || barrageType == BarrageType.night){
// Day and night are a single sentence
NextBarrageArr();
}else if(barrageType == BarrageType.success || barrageType == BarrageType.fail){
// Success, failure
if(curBarrageArr.desc != " Specific scene barrage "){
NextBarrageArr();
}else{
if(index < baragesArr.Length){
StartCoroutine(nextBarrage());
}else{
isStop = true;
}
}
}
}
Create a barrage instance createItem, After creating a single instance of the bullet screen, the incoming data is initialized :
// Create a barrage UI
IEnumerator createItem(){
GameObject _obj;
_obj = GameObject.Instantiate(item);
_obj.SetActive(true);
_obj.transform.SetParent(scroll_rect.content.transform);
item.GetComponent<RectTransform>().localScale= Vector3.one ;
_obj.GetComponent<BarrageItem>().setData(curBarrage);
yield return new WaitForSeconds(0.1f);
scrollViewNevigation.Nevigate(_obj.GetComponent<RectTransform>(), Mathf.Min(0.8f, ((float)min)/2));// Jog to the bottom of the scroll area
}
Single barrage example
Create script BarrageItem, Carry out simple assignment and initialization .
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class BarrageItem : MonoBehaviour
{
public Text userName;
public Text text;
public void setData(BarrageItemJson data){
userName.text = UserNameClass.GetRandomName().nickName + ": ";
text.text = data.desc;
}
private void Update() {
GetComponent<RectTransform>().localScale = Vector3.one;
}
}
Final effect
版权声明
本文为[Ben Boli]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230231315986.html
边栏推荐
- Preliminary understanding of stack and queue
- So library dependency
- Explain JS prototype and prototype chain in detail
- [suggestion collection] hematemesis sorting out golang interview dry goods 21 questions - hanging interviewer-1
- Day 3 of learning rhcsa
- 牛客手速月赛 48 C(差分都玩不明白了属于是)
- How to prevent leakage of operation and maintenance data
- [nk]牛客月赛48 D
- How to solve the complexity of project document management?
- 解决 注册谷歌邮箱 gmail 手机号无法用于验证
猜你喜欢
How to prevent leakage of operation and maintenance data
下载正版Origin Pro 2022 教程 及 如何 激 活
一个国产图像分割项目重磅开源!
009_ Redis_ Getting started with redistemplate
Yes, from today on, our fans can participate in Netease data analysis training camp for free!
Day18 -- stack queue
013_ Analysis of SMS verification code login process based on session
Flink stream processing engine system learning (II)
MySQL JDBC programming
Those years can not do math problems, using pyhon only takes 1 minute?
随机推荐
PTA: Romantic reflection [binary tree reconstruction] [depth first traversal]
Interpretation of the future development of smart agriculture
011_ Redistemplate operation hash
Implementation of distributed scenario business operation log (based on redis lightweight)
Intelligent agricultural management model
They are all intelligent in the whole house. What's the difference between aqara and homekit?
小程序 canvas 画布半圆环
The second day of learning rhcsa
MySQL JDBC编程
十六、异常检测
002_ Redis_ Common operation commands of string type
leetcode 烹饪料理
Consider defining a bean of type ‘com.netflix.discovery.AbstractDiscoveryClientOptionalArgs‘
数仓建表111111
R language advanced | generalized vector and attribute analysis
Understanding process (multithreading primary)
After idea is successfully connected to H2 database, there are no sub files
php+mysql对下拉框搜索的内容修改
Talk about current limiting
[XJTU computer network security and management] Lecture 2 password technology