当前位置:网站首页>Unity beginner 2 - tile making and world interaction (2D)
Unity beginner 2 - tile making and world interaction (2D)
2022-07-29 07:57:00 【Lin Fusheng】
This article comes from learning chutianbo Teacher's notes , link b standing The first 56P to 71P
1. Tile map making
Right click the main interface SenceGameObject2D ObjectTilemapRectanglar( This creates a RPG A visual angle )
establish tiles Folder Drag the material into the Purple Button opened in the upper right corner TIle Palette, Drag the material into
Or create it directly in the folder
2. What if the material is too large and needs to be divided
Back to the material change Sprite Mode by Multiple
Get into Sprite Editor Choose the top left corner Slice choice Grid By Cell Size
3. Tiles do not fit the frame
Go back to the material and find Pixels Per Unit Change it to 64 Match border
4. About the tiles covering the characters
go back to Hierarchy Under the Grid Under the tilemap Find the one on the right TIlemap Renderer change order in layer by -10( Put the layer behind )
5. About regular tiles
stay tile Right click in the folder Create2DTilesRule TIle( If there is no probability, there is no plug-in , Find other articles to teach directly )
6. How to quickly make tiles with similar rules
Above , choice rule Overring tile
7. How to connect the collision bodies of tiles ( Originally, the tiles we made were all separate collision bodies )
In the fourth part tilemap Add Composite Coillider 2D Components
stay TIlemap Collider 2D The admission used by Compite that will do ;
8. About rules like tile inheritance
Direct inheritance rules are similar to tiles , Then whether the collision body is also inherited , So if there are different collision bodies, it needs to be remade
9. Implementation of pseudo perspective
stay 2D In the game , In the scene “ Before and after ” By Y Axis determined , Need make Unity According to the game object y Coordinates to draw game objects
Y Axis y The smaller the coordinate value , The more forward , Should cover y Game objects with large coordinate values , That is to say y Draw the game object with smaller coordinates , Will be on the upper floor
In the game , If you want to set 2D Pseudo perspective attempts to , It needs to be changed in the project settings :
Edit > Project Settings > Graphics > Camera Settings > Transparency Sort Mode = Custom Axis > Transparency Sort Axis x = 0 / y = 1 / z = 0
So the material we use should also be in Sprite Mode Under the Sprite Edito Center axis ( Personally, I think it's a covering point ) Put it on the foot of the character .
2 About the implementation of collision
If an object needs to collide, it must have a rigid component, that is Rigidbody 2d(2d This is in the game )
Similarly, if he needs to interact with other objects , Then he also needs collision body components Box Collider 2D
2.1 After adding two components, the character drops rapidly
Close Gravity Scale( gravity ), Set it to 0 that will do ;
2.2 stay 2dRPG For perspective effect, it is best to set the collision box around the foot ( Probably the body 1/3 about )
3 Add life systems to our characters
This is very simple , In the script we added for role control in the previous section
public int maxHealth = 5;
public int currentHealth;
void Start()
{
// Get the rigid body component of the current game object
rigidbody2d = GetComponent<Rigidbody2D>();
// Initialize the current health
currentHealth = maxHealth;
}
3.1 It is very dangerous to directly expose the important life values in our game , This value should not be directly called externally
So we need to deal with currentHealth encapsulate . That is, use attributes to protect its internal fields
int currentHealth;
public int Currenthealth
{ get { return currentHealth; } }
//set { currentHealth = value; } }
In this way, we have a simple life system
4 The interaction of the world
After having the life system , Life will change because of the player's operation , So we need to add the function of player life change
public void changehealth(int amount)
{
// Limit HP to 0 To maxhealth Between
currentHealth = Mathf.Clamp(currentHealth + amount, 0, maxHealth);
Debug.Log(" Current health :" + currentHealth + "/" + maxHealth);
}
Here we use unity Self contained Math.Clamp function , This will limit the amount of blood to 0 To the maximum HP
link Official documents :Math.Clamp
4.2 So after having this function , We can set blood bottles or traps for blood loss in the created world , Then the following code realizes eating a blood bottle to return a drop of blood to the player , At the same time, do not eat blood bottles when full of blood , And the function that the blood bottle disappears after eating it
public class Healthcollable : MonoBehaviour
{
// Record the number of collisions
int collideCount;
public int amount=1;
private void OnTriggerEnter2D(Collider2D other)
{
collideCount += 1;
Debug.Log($" What collides with the current object is {other}, The first {collideCount} This collision ");
// obtain Ruby object
RubyController rubyController = other.GetComponent<RubyController>();
// Detect who hit the blood bottle
if (rubyController != null)
{
// If Ruby Not full of blood
if (rubyController.Currenthealth < rubyController.maxHealth) {
rubyController.changehealth(amount);
// Vanishing blood bottle
Destroy(gameObject);
}
else
{
Debug.Log("Ruby No need to add blood ");
Debug.Log(" Current health :" + rubyController.Currenthealth + "/" + rubyController.maxHealth);
}
}
else
{
Debug.Log(" Not Ruby object ");
}
}
}
OntiggerEnter2D Function is a function that triggers only once when entering ;
4.3 In the same way, we are setting up an area where blood will fall when encountering
public class Damageable : MonoBehaviour
{
// Blood loss
public int DamageNum = -1;
// Entering the range triggers once
private void OnTriggerStay2D(Collider2D collision)
{
RubyController rubyController = collision.GetComponent<RubyController>();
if (rubyController != null)
{
rubyController.changehealth(DamageNum);
}
else
{
Debug.Log(" Not Ruby object ");
}
}
// Every frame triggers
}
OnTriggerStay2D It is a function that will trigger every frame in the collision body , In this way, we will find that the character loses blood too fast , Almost instantly, the blood volume is empty .
So we add a short-term invincible function to the character after receiving damage
// Set invincible interval
public float timelnvincible = 2.0f;
// Set whether it is invincible
bool islnvincible;
// Defining variables , Invincible time ( timer )
float invincibleTimer;
stay update Add the detection of invincible ( In fact, I think it seems unreasonable to detect this function every frame )
void Update()
{
// The invincible moment enters the countdown
if (islnvincible)
{
invincibleTimer -= Time.deltaTime;
if (invincibleTimer < 0)
{
islnvincible = false;
}
}
}
Add an invincible code snippet to the life changing function written above
// Change health
public void changehealth(int amount)
{
if (amount < 0)
{
// If invincible , Then jump out of the function directly , Otherwise, players will enter invincible , Timing begins
if (islnvincible)
{
return ;
}
islnvincible = true;
invincibleTimer = timelnvincible;
}
// Limit HP to 0 To maxhealth Between
currentHealth = Mathf.Clamp(currentHealth + amount, 0, maxHealth);
Debug.Log(" Current health :" + currentHealth + "/" + maxHealth);
}
This article is only a preliminary study of personal records unity used
link Teacher's document : Tile world
边栏推荐
- The smallest positive number that a subset of an array cannot accumulate
- [cryoEM] Introduction to FSC, Fourier shell correlation
- Credit card shopping points
- Jiamusi Market Supervision Bureau carried out special food safety network training on epidemic and insect prevention
- Go, how to become a gopher, and find work related to go language in 7 days, Part 1
- Measured waveform of boot capacitor short circuit and open circuit of buck circuit
- Jump from mapper interface to mapping file XML in idea
- In an SQL file, a test table and data are defined above, and you can select* from the test table below
- Write some DP
- Technology sharing | quick intercom integrated dispatching system
猜你喜欢

RoBERTa:A Robustly Optimized BERT Pretraining Approach

How to draw an excellent architecture diagram

IonIcons图标大全

Amaze UI 图标查询

Jianmu continuous integration platform v2.5.2 release

Day 014 2D array exercise

Jiamusi Market Supervision Bureau carried out special food safety network training on epidemic and insect prevention

JVM garbage collection mechanism (GC)
![[deep learning] data preparation -pytorch custom image segmentation data set loading](/img/7d/61be445febc140027b5d9d16db8d2e.png)
[deep learning] data preparation -pytorch custom image segmentation data set loading

10 practical uses of NFT
随机推荐
The new generation of public chain attacks the "Impossible Triangle"
Vmstat memory consumption query
Some thoughts on growing into an architect
How to draw an excellent architecture diagram
String class
Phased learning about the entry-level application of SQL Server statements - necessary for job hunting (I)
10 common software architecture modes
Android interview question | how to write a good and fast log library?
Embroidery of little D
My entrepreneurial neighbors
工业互联网行至深水区,落地的路要怎么走?
Excellent urban design ~ good! Design # visualization radio station will be broadcast soon
Pytorch's skill record
[cryoelectron microscope] relion4.0 pipeline command summary (self use)
Sqlmap(SQL注入自动化工具)
[memo] summary of the reasons why SSH failed? Remember to come next time.
The smallest positive number that a subset of an array cannot accumulate
【无标题】格式保存
How to get to the deep-water area when the industrial Internet goes?
Solve the problem that CSDN cannot publish blog due to unknown copyright