当前位置:网站首页>Cocoscreator old, live and new - synthetic large zongzi
Cocoscreator old, live and new - synthetic large zongzi
2022-06-10 01:08:00 【sesame seeds】
- Click the jump =>《 Navigation post 》- Unity manual , Systematic practical learning
- Click the jump =>《 Navigation post 》- Android manual , Revisit mobile development
This article is about 9 Thousand characters , Novice reading needs 27 minute , Review needs 12 minute 【 Collect at any time, no longer get lost 】
About author
as everyone knows , Life is a long process , constantly overcome difficulties , Constantly reflect on the process of progress . In this process, there will be a lot of questions and thoughts about life , So I decided to put my thinking , Share all your experiences and stories , To find resonance !!!
Focus on Android/Unity And various game development skills , as well as Share various resources ( Website 、 Tools 、 material 、 Source code 、 Games etc. )
If you need anything, welcome me , Communication groups make learning No longer alone .
Premise
【 In order to facilitate quick understanding , Xiao Kong specially uses Chinese if he can use Chinese , Convenient for the masses 】
【 Friendship tips : Try to use English 】

Practice process
Launch page
First, we create the launch page scene_start, Then we add the background sprite ( It's monochrome - Only modify the color attribute ) And two buttons ( Start and exit the game )
Set the two buttons to NormalSprite、PressedSprite And so on , Then press the button of the sub node Label The text is set to the corresponding Chinese character ( The font style is set to white bold and italic )

Then drag to the corresponding position :

Then add a score display box , This score change must require our code to control the display , So first create a MaxScore The script is mounted on it , We'll talk about the script later .

Cute animation
The basic homepage above is fine , Then let's add some vivid animation , Make the whole interface look more advantageous .
- 1. Create an empty node mount Animation Components , stay assets Create in folder Anim file
- 2. take Anim The document points to Animation Of Clips
- 3. Then edit Anim file

Directly in 【 Background animation 】 Add multiple... Under the node Sprite Components , Then give them different sizes and different image materials .

Then go to the animation editor page , For simplicity, we will add animation directly to the outermost node , We added a zoom animation for him (1->0.8->1), Scale dimensions from 1 To 0.8 Until then 1, The overall duration of the animation is 1s( second ),PingPong Form of animation ( Ping Pong form back and forth ).

All right. , The home page basically has a shape .
Core script
Then we create two scripts (ScriptStart and ScriptMaxScore)

ScriptStart The script contains two methods , They are loading the next scene and ending the game , The above two buttons call , And then in onLoad Method , If yes, read the corresponding. If not, set it to 0( prevent ScriptMaxScore The script read value is null )
protected onLoad() {
console.log("ScriptStart Of onLoad");
// The consideration of data encryption can only be server
if (localStorage.getItem(ScriptStatic.MaxScore) == null) {
console.log(" No highest score ")
// Why not set it here when you don't have it
localStorage.setItem(ScriptStatic.MaxScore, "0");
} else {
console.log(" With the highest score ", localStorage.getItem(ScriptStatic.MaxScore))
}
}
// Start the game - Load the next scene
GameStart() {
director.loadScene("scene_game");
}
// End the game
GameExit() {
game.end;
}

Note appended : The life cycle of the script and Unity be similar , All the scripts are finished onLoad Go down to all the scripts onEnable Then there are all the scripts start, And so on . Their same life cycle function execution order is affected by the order in the hierarchical Manager .

Scores we use WordArt to show , There are two ways to set up WordArt :
One is to directly generate the corresponding bitmap font file
One is that the wizard creates multiple images for a preform code and sets corresponding images for each
We use the first method .
Create a text bitmap font (fnt and png Two documents )- I don't know how to create it. You can confide in me .
Then assign the font to Label Component's Font attribute , Remember to revise CacheMode, By the way, by the way Layer Whether it is right , Xiao Kong was trapped here once ( It never shows, but it feels right everywhere , It turned out that the low level was covered by the background .)


Then we get the script for the score node ScriptMaxScore
start() {
console.log("ScriptMaxScore Of start");
// Read the saved score data , This one is in Start Of onLoad Set in One is to set at the end of the game
let score = localStorage.getItem(ScriptStatic.MaxScore)
// Set fraction WordArt
let LabelScore = this.node.getComponent(Label);
if (LabelScore != null) {
LabelScore.string = score + "".toString();
} else {
console.log(" Get text node is empty ")
}
}
Game main interface
After the previous two sections , This is the start page, and we're done , Then you will enter the content of the game .
Let's first analyze the specific playing methods :
- 1. The content style of the next small ball can be previewed in advance in the upper right corner of the page
- 2. No new ball shall be released until the current ball has fallen , Prevent too fast
- 3. It is not allowed to exceed the boundary at the bottom of the left and right sides , There's a grid ( Collision shoulder rub )
- 4. The small ball has the property of free fall and appropriate rebound effect
- 5. Play the appropriate audio and merge effect during the small ball merging process
- 6. When exceeding the upper boundary, there should be the judgment of loss and the display of score
- 7. You can restart the game and return to the home page
So let's add a background , Left wall , Right wall , And the bottom floor , The position is just right, wrap the back .
So that the objects inside don't fall out of bounds , Need to add impactor to the wall (BoxCollider2D) And rigid body components (RigidBody2D)

Realize return and replay
Before scene transformation , Both of them need to judge whether the current score is greater than the highest score in history , If it is greater than, the current score will be saved and replaced , Otherwise, you can leave it alone . And then use it 【director.loadScene】 Just load the scene .
by the way , Don't forget to assign click events to the buttons in the scene .
// Play the game again
GameRePlay() {
// Also judge whether to save the data
let MaxScore = localStorage.getItem(ScriptStatic.MaxScore);
if (MaxScore != null) {
// Compare the current score with the saved score. If it is larger Save If it's not big, don't save
//parseInt The second parameter represents hexadecimal
if (parseInt(MaxScore.toString(), 10) < ScriptStatic.CurrentScore) {
localStorage.setItem(ScriptStatic.MaxScore, ScriptStatic.CurrentScore + "");
}
}
// Save the score first
ScriptStatic.CurrentScore=0;
director.loadScene("scene_game");
}
// Return to the previous scene
ClickBack() {
let MaxScore = localStorage.getItem(ScriptStatic.MaxScore);
if (MaxScore != null) {
// Compare the current score with the saved score. If it is larger Save If it's not big, don't save
//parseInt The second parameter represents hexadecimal
if (parseInt(MaxScore.toString(), 10) < ScriptStatic.CurrentScore) {
localStorage.setItem(ScriptStatic.MaxScore, ScriptStatic.CurrentScore + "");
}
}
director.loadScene("scene_start");
}

Small ball preform
You know, you have to create a small ball every time , And there is a preview in the upper right corner , So we need a preform , Later, it is realized by instantiating the preform , And when the preform is initialized, it can automatically random different small balls .
Right click to create a 2D Of Sprite, add to 【CirleCollider2D】 and 【RigidBody2D】 Components , Rigid body components can be selected by default , The impact component needs to modify the lower friction coefficient 【Friction】 And elastic coefficient 【Restitution】, One 【0.2】 One 【0.3】 Well .【Radius】 The radius needs attention , Different melons have different radii , In addition, it fits well when it comes back during collision , This radius needs to coincide with the picture. It's best , Not big or small .
By the way, let's add a coefficient of elasticity , In this way, the rebound effect is more Q La .
Then add a script , Let's think about the function of changing the script
- 1. Automatically change different spheres
- 2. Changes the shape of the current sphere Collider radius , This can achieve good collision detection
- 3. Watermelon collision event and post collision merger
- 4. Detection and judgment of death line
// Get Sprite
let thisSprite = this.node.getComponent(Sprite);
if (thisSprite != null) {
thisSprite.spriteFrame = this.spriteFrames[index];
} else {
console.log("changeBall Of thisSprite It's empty ")
}
// Dynamically change the radius of the created preform
let PrefabCollider = this.node.getComponent(CircleCollider2D);
if (PrefabCollider != null) {
if (index == 0) {
PrefabCollider.radius = (54 / 2 -1);
}
//…… Elliptic logic
ScriptStatic.CurrentBallRadius=PrefabCollider.radius;
} else {
console.log("changeBall Of PrefabCollider It's empty ")
}
Collision detection
We use 2D And directed at Collider Registered listener
TempCollider.on(Contact2DType.BEGIN_CONTACT, this.MethodColliderEnter, this);
【MethodColliderEnter】 The method is our logical processing , It contains three parameters 【selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null】, There is an introduction in the official documents , In this small space, I don't hi myself . Please refer to the source code for logic details , The notes are very detailed .
Watch out! :
For the collision event to take effect , The monitor must be turned on in the rigid body component of the object 【EnabledContactListener】, Out of line .
Destroy or update a component in a collision event 【setTimeout】 To achieve the next frame modification , Because the modification of the current frame will report an exception .
In the logic function of collision detection, we use labels 【TAG】, And make use of 【TAG】 If you do something , So we should pay special attention to , Some nodes are in the scene 【TAG】 The default is 0, It is easy to misoperate the object . So we modify the scene 【 background _ Left wall 】 and 【 background _ Right wall 】 as well as 【 background _ ground 】 Collision component 【TAG】 by 100.
Then our main script uses him .
The main script of the game
The script is mounted on the yellow background , At the beginning and end, we need to register and unregister click events . Click the logic in the event :
- 1. Initialize the preform
- 2. Set location
- 3. Randomly generate spheres
- 4. Preview the generation in the upper right corner
For details, please refer to... In the source code 【onClickStart】 Method
Be careful :
UI If the script on wants to respond to click events , There are... On the object that must be mounted 【UITransform】, And in Canvas Next
Update score
【 fraction 】 Mount on node 【ScriptScore】 Script , The script directly opens a timing that is updated every second , Take the previously saved score variable .
But that doesn't satisfy us , Our display must be elegant , you 're right , grace .

So we need to use artistic numbers , At the beginning of this, the maximum score of our startup page is the technology of communication first .
Find our 【number.fnt】 The file is assigned to 【Label】 Of 【Font】, Then add... To the code
this.schedule(()=> {
// Set fraction WordArt
let LabelScore = this.node.getComponent(Label);
if (LabelScore != null) {
LabelScore.string = ScriptStatic.CurrentScore + "".toString();
} else {
console.log(" Get text node is empty ")
}
}, 1);
Death sentence
Trigger when touching the top line . therefore UI There should be collision detection , And the response processing needs to be carried out according to the event callback .
We add 【RigidBody2D】 and 【BoxCollider2D】, Be careful : If you want the system to call a callback , Need to activate 【EnabledContactListener】, Then in the script 【onLoad】 Registered events in . The code is as follows :
protected onLoad() {
let TempCollider = this.node.getComponent(BoxCollider2D);
if (TempCollider != null) {
console.log(" The death line registered the collision event ")
TempCollider.on(Contact2DType.BEGIN_CONTACT, this.MethodColliderEnterDeath, this);
} else {
console.log(" dying Collider It's empty ")
}
}
start() {
// [3]
}
/** * Pay attention You don't need to respond to the above RigiBody2D Of Type Static type It can't be the default * @param selfCollider * @param otherCollider * @param contact * @constructor * @private */
private MethodColliderEnterDeath(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
console.log(" Executed the collision of the death line ")
// Determine whether to save the score for the maximum value
let MaxScore = localStorage.getItem(ScriptStatic.MaxScore);
if (MaxScore != null) {
// utilize Number() Convert the string to number You can compare the size
if (Number(MaxScore) < ScriptStatic.CurrentScore) {
localStorage.setItem(ScriptStatic.MaxScore, ScriptStatic.CurrentScore + "");
}
}
// Show the death interface
if (this.NodeDeath != null) {
this.NodeDeath.setPosition(0, 0, 0);
} else {
console.log(" The death interface is empty ")
}
// No more click responses in the background
if (this.NodeBg != null) {
let TempScript = this.NodeBg.getComponent(ScriptGame);
if (TempScript != null) {
console.log(" Click event canceled ");
// this.NodeBg.off(Node.EventType.TOUCH_START, TempScript.onClickStart, this);
TempScript.IsDeath=false;
} else {
console.log(" The obtained script is empty ")
}
} else {
console.log(" The death interface is empty ")
}
}
thus , Our whole development process is over .
other
author : Xiaokong and Xiaozhi Xiaokong
Reprint note - Be sure to indicate the source :https://zhima.blog.csdn.net/
This Taoist friend, please Step back ️, I watch you Extraordinary bearing , There is a king's domineering spirit in his speech , There will be a great achievement in the future !!! There is give the thumbs-up Collection Today I tell you , Have you ordered it , Your success in the future ️, I don't take a penny , If it doesn't work ️, Or come back to me .
reminder : Click the card below to get more unexpected resources .
边栏推荐
猜你喜欢

进阶自动化测试的看过来,一文7个阶段5000字带你全面了解自动化测试
![The binary tree is expanded into a linked list [the essence of tree processing -- how to handle each sub tree]](/img/b3/5a7c20fad1fd17ef82ed730d686723.png)
The binary tree is expanded into a linked list [the essence of tree processing -- how to handle each sub tree]

内网渗透隧道

FPGA-VGA显示

Chapter 6 domain controller security

花了两小时体验IDEA最新史诗皮肤

Gartner global IAAs report in 2021: AWS cake is nibbled, and Chinese cloud manufacturers are steadily attacking

第5章域内横向移动分析及防御

Mysql——》事务的隔离级别

JVM -- class file
随机推荐
Gartner global IAAs report in 2021: AWS cake is nibbled, and Chinese cloud manufacturers are steadily attacking
洛谷P1028 数的计算 题解 动态规划入门题
LEAK: ByteBuf. release() was not called before it‘s garbage-collected
沪漂大专程序员,一边跟刘畊宏健身,一边拿22k的offer
Sword finger offer II 020 Number of palindrome substrings
总结——》【JVM】
PCI bar register explanation (I)
How to optimize slow queries? (actual combat slow query)
JVM -- class file
Mysql——》varchar
Intranet penetration Chapter 4
洛谷P1220 关路灯 题解 区间DP
Esri整合LightBox数据以扩展加拿大境内的地理编码
线性规划和对偶规划学习总结
Hcip first job
Have you learned about arrays and slices in golang in go question bank · 1?
内网渗透隧道
劍指 Offer II 018. 有效的回文
MySQL - separate database and table
剑指 Offer II 021. 删除链表的倒数第 n 个结点