Unity Cookbook. 2D Basics
2D Basics
Using Unity for 2D games
- Manual: 2D or 3D
- Manual: 2D and 3D Mode settings
- Manual: 2D Game Development Quickstart Guide
- Unity is first and foremost a 3D engine (x, y, z)
- there is no dedicated 2D (x, y) mode
- There is a dedicated
Vector2
class for 2D vectors- Some vectors used in 2D, like
transform
are stillVector3
- Some vectors used in 2D, like
2D Project template
- When creating a new project, you can choose a 2D project template
- IT’S STILL SECRETLY 3D, the z axis is just disregarded
- It basically just adjusts the Unity UI
- some 2D GameObject templates, like sprites and tilemaps available
- You can change between 3D and 2D view modes by pressing the 2D button in the Scene view
Useful 2D GameObjects
- Sprites
- 2D Primitives
- For drawing basic shapes in 2D
- Manual: 2D Primitives
- Sprite Shape Asset
- Curve-based graphics & collision
- Manual: Sprite Shape
Camera component
- 2D camera needs to be orthographic
Collision & Physics components
- Colliders
- See: Collision
- Remember to use the 2D versions of colliders:
- PolygonCollider 2D, CircleCollider 2D, …
- RigidBody 2D
- See: Physics
- Effectors
Sprite Renderer component
- 2d images in games are called sprites
-
They’re drawn on screen with the Sprite Renderer component
Example: Using Sprite Assets
1) Create a .png image file 2) Add it to your Assets folder 3) Click it once to see its properties in the Inspector. Set the values:
- Set Texture type to Sprite (2D and UI)
- Pixels per unit value tells how big the sprite should be on screen
- If you’re using pixelart, you need to take some more things into consideration
- See: Pixelart in Unity
- Click Apply 4) Drag it from the Project window into the Sprite field in the Sprite Renderer component
Other renderer components
- Line Renderer
- Use for drawing a line on screen
- Manual: Line Renderer
- Trail Renderer
- For drawing trails
- Manual: Trail Renderer
- Sprite Shape Renderer
- Draw images along a path, or just paths
- Sprite Shape Renderer
Extra: Two ways for 2D shooting
- Brackeys video: 2D shooting
- For slow bullets: Instantiate a bullet prefab
- For instant hit: Raycasting (see example below)
RaycastHit2D hit = Physics2D.Raycast(line.transform.position, line.transform.up, lineDistance);
Extra: Moving on a grid
For grid-based movement, see this thread: Unity answers: Moving on a grid