Unity2D Getting Started Tutorial
Tutorial source: Bilibili Up main course: Unity Tutorial Introduction to the first game production
The following are all based on 2D games
common operations
general operation
save game state
Modify the parameters of the component in the Inspector while the game is running, click the upper right corner of the component, select Copy Component,
After the game is running, click the upper right corner of the component and select Paste Component Values to save the runtime parameters
Mapping with TileMap
TileMap creation : Hirerachy > right click > 2D Object > TileMap
Create a palette : Window > 2D > Tile Palette
-
Drag the image into the palette to turn it into a Tile file, and then use the palette tools to draw a map
-
Tile files can be stored in Environment and create a new map directory
Pixels Per Unit : The selected sprite resource will be seen in the Inspetor panel, indicating how many pixels there are in a row or column in a Unity unit
- If there is a gap between the tiles after the tiles are dragged onto the interface, you can adjust this parameter
Cutting Atlas : Select a sprite image resource, change the SpriteMode from single to mutiple, it can be made into an atlas, and then click SpriteEditor to cut.
There are three forms of cutting: automatic, cutting by pixel, cutting by row and column
- For a relatively large sprite image, we drag it onto the Scene and it seems to take up a relatively large space. In fact, it only occupies one grid. In order to make it look as large as the actual occupation, we need to cut this image into an atlas
- For this seemingly large picture, use row and column cutting to cut into small grids
Realize the collider effect
Rigidbody: Rigid body components, which enable game objects to gain gravity and accept external force and torsion functions
BoxCollider: The collider component, which enables the game object to have the ability to collide with the game object that mounts the rigid body component
Realize the collision effect : add Rigidbody 2D and Box Collider 2D components to characters, and add Tilemap Collider 2D components to Tilemap
Rotation effects are not allowed : Rigidbody 2D > Constraints > Freeze Rotation
Mobile bug fixes
If you add a square Collider to the whole character, it will get stuck when moving. The solution is to use a circular Collider for the lower body
Realize character control
Input button settings: Edit > Project Settings > Input Manager, where you can change the buttons mapped to each axis
GetAxis
Get decimals between [-1, 0], [0, 1]:
float horizontalMove = Input.GetAxis("Horizontal");
GetAxisRaw
Get a value in -1, 0, 1
float faceDirection = Input.GetAxisRaw("Horizontal");
GetButton
It can detect that the user presses a function key, such as Jump - Jump
if (Input.GetButton("Jump"))
{
rb.velocity = new Vector2(rb.velocity.x, jumpForce * Time.deltaTime);
}
animation system
Open the animation panel : Window -> Animation -> Animation
- The animation panel is used to make animations, drag a series of pictures in to make animation effects
Open the animator panel : Window -> Animation -> Animator
- The animator panel is used to link state transitions between animations
Add animation effects :
1. Add the Animator component to the game component
2. Create a folder for storing animations, and create an Animator Controller in the folder to control animations
3. Drag the Animator Controller to the Animator component
4. Select the game component, create an idle animation in the animation panel, and drag the animation picture into
Realize running animation :
1. Create a run animation
2. Create a transition between the animator panel, run and idle (make transition)
3. Add parameters in Parameters running
, float type
4. For the transition of idle -> running, remove Has Exit Time, set Transition Offset to 0, and set Conditions torunning > 0.1
Running -> idle is the same, Conditions arerunning < 0.1
5. According to the Conditions set for the transition above, assign a value animator.SetFloat()
to to control the running animation
Implement jumping and landing animations :
1. Create jump animation and fall animation
2. In the animator panel, create transitions between animations (make transition)
3. Parameters add parameters jumping
, falling
, Bool type
4. In the transitional Inspector, remove Has Exit Time and set Transition Offset to 0
The Conditions for the transition to jump are jumping = true
; the Conditions for the transition to fall arefalling = true
5. According to Conditions, write code
public Rigidbody2D rb; // 刚体
public BoxCollider2D coll; // 碰撞体
public Animator animator; // 动画器
public LayerMask ground; // 地面图层
...
// 检查并切换动画状态
void SwitchAnim()
{
// 处于跳跃状态
if (animator.GetBool("jumping"))
{
// y轴的力没有了
if (rb.velocity.y < 0)
{
animator.SetBool("jumping", false);
animator.SetBool("falling", true);
}
}
// 处于降落状态, 碰撞了地面
else if (coll.IsTouchingLayers(ground))
{
animator.SetBool("falling", false);
animator.SetBool("idle", true);
}
}
6. The in the code public LayerMask ground
refers to the layer where the game object is located:
In order to detect the collision ground, you need to set a layer Group for the Tilemap, and get it in the code:
camera control
script control
This method is to add a script to the Main Camera so that the x and y of its Transform are consistent with the player at all times.
Whether y needs to be consistent mainly depends on the requirements of the game. For example, the camera will not move when Super Mario jumps up, and the camera will follow after jumping up in Castlevania.
public class CameraController : MonoBehaviour
{
public Transform player;
void Update()
{
transform.position = new Vector3(player.position.x, 0, -10f);
}
}
Cinemachine
First install Cinemachine in Package Manager, then there will be one more Cinemachine on the top menu
Background follows :
1. Cinemachine > Create 2D Cinemachine, create a CM vcam 1 object
2. Drag the game object to follow to CM vcam 1 > Follow in Inspector
Some parameters in the Inspector:
-
Lens > Orthographic Size: Adjust the lens size
-
Body > Dead Zone: A section of the area that the camera will not follow, beyond this area it will automatically follow
-
…
Limit the area to the background :
-
CM vcam 1 > Inspector > Add Extension > Cinemachine Confiner
-
You need to specify a Collider for the above component, and add a Collider to the Background (check isTriger)
Use Polygon Collider here
-
CM vcam 1 > Inspector > Cinemachine Confiner > Bounding Shape 2D is designated as Background Collider
add items
The method of adding game objects on the interface :
- Create a Sprites, drag the item material to it, remember to modify the corresponding level
Animation effects added to items :
- Add the Animator component to the object, create an Animate Controller in the folder and drag it to the Animator on the object
- Create animation effects in the animation panel
Add collision destroy event to items
-
Add a Box Collider 2D component to the item, and check the isTrigger
If you don’t check isTrigger, you can’t hit it like a wall. After you check it, you can perform some touch events (with
OnTriggerEnter2D
functions ) -
Set the Tag to the object as Collection
// 碰撞事件
private void OnTriggerEnter2D(Collider2D collision)
{
// 如果碰撞到的物体标签是Collection,则销毁
if (collision.CompareTag("Collection"))
{
Destroy(collision.gameObject);
}
}
Make prefab
Create a Prefabs folder, drag the finished Cherry item into this folder, and use the finished item as a template to create other items repeatedly (the function is the same)
If you don’t use Prefabs, you need to perform a lot of repetitive operations every time you add an item. With Prefabs, you only need to copy
code understanding
Time.deltaTime
Represents the time difference between two frames.
update()
Although the method in the script runs every frame, the time interval between two frames is not necessarily equal when actually running.
For Rigidbody and Collider, almost every game object will not change after being mounted, so it is not necessary to declare it as publicc, and then assign it by dragging and dropping in Unity.
It can be directly declared as private and assigned in code.
[SerializeField]
It is possible to make private variables also show up in Unity.
[SerializeField] private Rigidbody2D rb;