Develop a 2D horizontal game demo with Unity

 

# LanW Game Project

5d211f15aba14b70ac770a6b275e9b94.jpeg

Table of contents

(1) Introduction

(2) Installation Tutorial

(3) Development process

1. New construction

2. Set the character

3. Control the movement of the main character

4. Add animation for switching actions

5. Camera Tracking

6. Collect objects

7. Create UI

8. Create the enemy

9. Make enemy ai

10. Creating the Frog Animation

11. Optimize code

12. Set sound effects

13. Make dialog

14. Making the Dead Boundary

15. Make scene transitions

16. Parallax Parallax

17. Create the menu

18. Make the audio track

19. Pack the game

(4) Common problems and solutions

(5) Thanks


 

 

(1) Introduction

This article mainly introduces how to use unity to develop a simple horizontal platform jumping game demo. The materials displayed in this game are all from the unity store. The development process shows only part of the reference code. All project files of the game and The code is at https://gitee.com/lan-dashai/lan-w-game-project/tree/master

Software environment
Visual stdio 2019 
Unity Hub;
editor version: Unity 2021.3.7f1c1(LTS);


(2) Installation Tutorial

1. First search the URL on the webpage: https://unity.cn/unity-ggac-2021
2. Click to download unity hub
3. Install the editor version

(3) Development process

1. New construction

*Search for a good package in the Asset Store and download it in the Package manager to download and import
*Change the Pixels Per Unit of the background image to 16 (each grid contains 16 pixels) and apply Drag the background image into the Level window to load and reset its position

The main interface is as follows

450a5bc22ca64e56aae76c092adc5485.png
 Create a new 2D obj Tilemap in the level
*Hide the background image for viewing Select Tile Palette in Window 2D
*Create a new one in the window and name it map Create a new folder named maps in the default jump folder
*Set the tile material For the automatic cutting of 16 Sprites, change the Mode to Mutiple. Click on the Sprite Editor. Click on the GridByCellSize Pixel in the window to set it to 16*16 and cut it.
After cutting, click Apply and drag it into the Tile Palette. Click the brush to draw the map (turn off edit) (use the eraser It can be erased and remember to select the current Tile map)
*Adjust the attribute size of the main camera to 6
Click on the background image to add a new Sorting Layer Name it Background and Frontground Set the background to BG

 

 

2. Set the character

*Change the character picture to 20, create a new 2D Sprite in the level, drag the character to the Sprite in the edit panel of Sprite Render and reset,
 click Add Component of the character to add Rigidbody 2D (the rigid body turns the paper into an object)
*Continue to create the character Add a Collider Box Collider 2D Click the icon (edit) that connects the three boxes and pull the green border to a suitable position
 Add a Tilemap Collider 2D to the map Now run the game and the character can stand on the ground

51da2068382c4ee1b40fd3a3189b6ada.png

b1708f990fcb4b529124ed32caf7af0c.png

 

d7488a1b6f7a4655be4854d36e18d39d.png

 

 

3. Control the movement of the main character

* Add code for the character Add New Scripts Name it PlayerController
Open the script
to create a rigid body public Rigidbody2D Rd; Drag the rigid body into the created rigid body
Create an initial velocity public float Speed; Set it to 10 to
create a movement method newfloat to receive the input GetAxis ( horizontal) if statement when it is not 0 (ie -1 or 1) the movement of the Rd.velocity rigid body = newVector2 (HorizontalMove * Speed, Rd.velogy.y); tick the
Freeze Rotation Z in the Constrains of the character rigid body (Freeze the z-axis) Otherwise, the rigid body will rotate when moving.
The speed parameter can be adjusted during the trial, but it will not be saved after the trial is over. You need to manually set it and
write code to modify the character orientation. Create a float in the movement method to accept the input GetAxisRaw (horizontal )-1 0 1 integer if statement When it is not 0, the transform.scale of the object (in unity) = new Vector3(FaceDirection,1,1); * (
optimized code) modify Update to FixedUpdate() to let the program in Run smoothly on a computer with frames below 60. After *Speed ​​and then save *Time.deltaTime, change the Speed ​​in the game to 400.
Write code to create the jumping force public float JumpForce Add an if statement to the Movement function if Input.GetButtonDown("Jump") then Rigidbody.velocity = (Rigidbody.velocity.x, JumpForce * Time.deltaTime); and set the JumpForce of the unity character Change the Gravity Scale of the rigid body to 2 for 400

dc86c0bd98b246edb8c212b73156e5e9.png

cc869d42797a402cb2729b06493c439f.png

e95b9889fdf44c1b920e8b4638b7d57d.png

 

 

 

4. Add animation for switching actions

*Add the Add Animator component to the character and create a new Animation folder to manage it. Create a new Animation Controller in the new Player folder below, name it Player, drag it into the Controller position in the component, and click Window Animation Animation to create Animation. Click Create to create and name it Idle
( Stand still) Change all the idle pictures in the Asset to 16 and drag them all into the timeline
*Set the sampling rate Samples (three points open) to 10 (or select all nodes and drag to a suitable length)
*Create a new Animation and name it Pay attention to the file storage location for Run. Open the Run picture of the character picture in Asset and change it to 16. Drag it into the timeline and change the sampling rate of Samples to 10 (Loop Time is checked by default)
. Select Float in the drop-down triangle of the Parameters component of the Animator component, add Float and name it Running
*Select the connecting line and uncheck Has Exit Time (no animation buffer will switch immediately) Change the Transition Duration in Settings to 0 (no conversion required Time) In Conditions, click the plus sign to add the value of the condition and change it to 0.1. 
Similarly, change the Greaterer of Conditions from Run to Idle to Less
*Write code to create a new variable public Animator Animator; add Animator.SetFloat( in the Movement function "Running", Math.Abs ​​(absolute value of the accepted Horizontal)) After saving, return to the character encoding component of unity and drag the Animator component into it
*Create Animation Jump and Fall Drag picture 16 into the Animator component and set up the connection (Run, Idle link Jump, Jump link Fall, Fall link Idle) *Add Prarmeters Jumping Falling Idle *Set the connection parameters (Run
and
Idle Jump when Jumping is true to Jump) (Jump’s Jumping is false and Falling is true to Fall) (Fall’s Falling is false and Idle is true to Idle) *Open PlayController script*Write code void SwitchAnimation if
(
Animator.GetBool ("Jumping")){If the y coordinate of the rigid body is < 0, set Jumping to false, and set Falling to true} *
Write code public LayerMask Ground; to get the ground, add a new Layer setting to Tilemap named Ground and select Player Set the Ground of the encoding component to Ground
*Write the code public Collider2D Collider2D; to obtain the character's collision body continue to write the elseif of SwitchAnimation (Collider2D.IsTouchingLayers(Ground)) {Set Falling to false, Idle to true} *Define Bool at the beginning of the function Animator.SetBool("Idle", false);
(Check the layer or elseif if there is flickering)!
*Reduce the Box Collider to the character Add the Cricle Collider collision body to the lower body position
*Write code to change Rigidbody and Animator to private and write their acquisition method in start = GetComponent<Rigidbody 2D>; = GetComponent<Animator>; (the name in <> is the name in the unity component) (add before the
definition [SerializeField] can make it visible and inoperable)

5a3de6437c9b40ffad58377638bbfae8.png

1cb8e2b89ee44ab0826c2c337cf1674a.png

 

 

5. Camera Tracking

*Add code for Main Camera Name it CameraControl
Add component Cinemachine Add a camera in the component menu Create 2D Camera Drag the player to Follow to follow (Dead Zone adjustment starts to follow the area Screen X/Y adjusts the fixed position of the character) ctrl d Copy the background
until Fill the screen, create a new Empty, name it BackGround, organize the three backs 
in the Add Extension component in 2DCamera, select CinemachineConfiner,
add Polygon Collider2D for BackGround, and set it to is Trigger (check it). Click Edit to pull the vertices of the polygon to the corners of the screen. Hold down ctrl and click to delete and add it to the Bounding Shape2D of the 2D camera

b63d5c26e812487aa9c2ba880e8147f2.png

 

6. Collect objects

*Create a folder for Cherry, change the picture material to 16, drag and import to add component Animator, create an AnimationController under the animation folder of Assets and name it Cherry, drag and import it into Animator, and create a new Cherry animation in the component editor. Drag in the picture
* Add Box Collider2D to Cherry Click Edit to adjust it to isTrigger (this is a device to detect whether it collides and don’t let it have a collision effect) *Create a
new Tag for Cherry called Collection
*Open the character’s code to create a new function In void OnTriggerEnter2D(), write the if statement if (collision.tag == "Collection") {Destory (collision.gameObject);} If the tag of the collision object is Collection, destroy the collision object * create a counter public int Cherry after
destruction write Cherry++;

8b49adb86be84d0f9ccba0091eea3b36.png

 

7. Create UI

*Create a new ui canvas UI Canvas in level1, right-click the Canvas, add UI Text, name it Cherry
f find the object position, move the Text to a suitable position, modify the Text content and adjust the appropriate size
*In the new UI Text, name it Numbers, modify the Text content and its attributes
to write The code obtains the ui text public Text CherryNumber; and drags the Number into it after saving it by using
*Add the code CherryNumber.text = Cherry.ToString(); in OnTriggerEnter
(fixed text position)
*Click the setting orientation map of the Cherry text (centermiddle icon ) and select the location as
the Number text in the upper left corner. The same operation
(create UI Image for Cherry and create UI, collision body and code for Gem)

3ba63f96b1e14d7abe80809f18066350.png

 

 


8. Create the enemy

*Create Enemy Frog, drag the frog picture into it, create its Idle and Jump animations, add Rigidbody 2D and Box collider 2D to it, and adjust the position of the collision body *Write the new function
private void OnCollisionEnter2D() {}
if statement when collision.gameObject.tag (If it is not a trigger type, you need to add gameObject) == "Enemy"; When Destory(collision.gameObject)
adjust the code to add new conditions && when the character is performing the Falling action
*Write code to add the character to get injured and retreat new public bool IsHurt; in Update Run Movement when if (IsHurt == false);
when the collision body hits the enemy && the x-axis of the character is smaller than the x-axis of the enemy (touching the enemy from the left), then IsHurt = true Character rigid body.Velocity = New Velocity(-10,y)
The opposite is the same on the right side
*Write the code when adding else if (IsHurt) in SwitchAnimation, if (the absolute value of the x speed of the rigid body <0.1f), IsHurt = false; (write above the falling code, otherwise it will keep running and falling) *
write The code adds animation code conditions in IsHurt and writes SetFloat("Running", 0); to ensure that it returns to normal action after the injury action is completed

 

9. Make enemy ai

*Add code private variable rb for Frog Get GetComponent<> in Start
*Add sub-items for Frog in heri as its moving area for easy observation and change their colors
*Write code to create IsFaceLeft Boolean value to observe that the left and right movement does not exceed The xy coordinate sub-objects of the left and right points are set to separate DetachChildren
* Write code to create xy, assign values ​​​​in Start, and destroy the two points after running
a73d853d9ffa470f96cb227913af5280.png

 

 

10. Creating the Frog Animation

*Add Jump fall animation connection for the frog respectively and set
*Write code to change the y-axis movement to JumpFoece Add a pre-if statement if rb.IsTouchingLayers (Ground) and turn on the jump animation to
automatically execute the jump Add event keyframes to the animation component controller Drag it to the end of the standing animation and set Function to the written Movement () and update the Movement comment in the code
*Write the code to add SwitchAnimation ()
if Jumping will change the jumping animation else if it hits the ground then turn off the falling animation
* Add the animation of the death of the frog. From the Any State connection, add the controller Trigger switch and name it Death
*Write the code to add the public Death function to the frog.
Add the EnemyFrog entity EnemyFrog Forg = collision.gameObject to the if statement in the if statement in the touch frog in the character animation. GetComponent<EnemyFrog>(); and use Frog to call Death
*Write code to add Destroy function Destroy(gameObject) for frog; Add key frame at the end of Death animation to enable destruction

c1982938fa9644c488c52d6aa9c67c24.png

 f8a70495bca94c478c2e2fa1b1822b72.png

 

 ed59a4204c874857946daf94013bf243.png

9864feea5b124d7db6824afe6c6e5e6a.png 

 

0d205011ca914376aa966287713e7307.png

 

11. Optimize code

*Create a new C# Enemy in the root directory, create a new variable protected Animator Anim; and obtain and adapt the Start Update function to protected virtual void Start() (protected virtual function) *Change EnemyFrog's: parent class to Enemy and change the variable of the
frog Get comments in Animator and its Start
* Set the frog's Start as protected override void Start () (override the parent class method) and call base.Start () in it at the same time
* Annotate and copy the Destory and Death functions into Enemy and All set to public
*Modify the code that destroys the frog in the character code, change the comment of the new frog to new Enemy, and change the bottom frog.destroy to Enemy.destroy

bfff420a7b5f42a2b60f8e45b14a68d2.png

 

12. Set sound effects

*Add component Audio Source for player Click overrides apply all in the upper right corner to add all newly added components to perfabs preset
*Drag and drop in AudioClip to add bgm Check Play on Awake (play when starting the game) Check loop (loop Play)
*Click the small arrow in the frog heri to enter the frog component to add AudioScouce 
*Write the code to create the explosion sound effect variable protected AudioSource DeathAudio in the enemy and getComponent to enable DeathAudio.play() in Death;
add various sound effects for the character in the same way Write the character code public AudioSource ____ and .play and drag in the sound effect in the component 

549a254c13ae4b71ab83b0571a9295c0.png

 

13. Make dialog

*Create a new UI Panel in the Canvas in level1 and name it EnterDialog
*Change the color and change the position to be fixed at the bottom, change the width to 600, height125 and change the Y axis to 100
*Create a sub-item for it, right-click UI Text, set the position, content, and text size
in Create a Trigger collision body on the door of the house (the dialog will appear when it touches the door)
* Write code to add the house code to create a variable gameObject Dialog 
* Write code to add functions OnTriggerEnter2D and OnTriggerExit2D if statement If the tag of the collision body is a player, then Dialog.SetActive (true/false); (Set switch)
(Make shallow in and out animation for text)
*Create an animation for EnterDialog in heri and name it EnterDialog
*Click the red circle to record the first transparent frame and the 20th frame appears to stop recording and run

 fdb17c7fb9bc4d4c9e4f3046aa30b3cd.png

 8dbb395b77a64093936abfe1a5776763.png

14. Making the Dead Boundary

*level1 creates a new project DeadLine and puts it under the layout, adjusts the length and adds its label and changes it to DeadLine
*Write code using UnityEngine.SceneManagement;
*Add an if statement in the character TriggerEnter2D when collision.tag == "DeadLine ";
ScenManager.LoadScene(SceneManager.GetActiveScene().name);
* Improve the code and create a new function Restart() to cut the switching scene into it
* Add Invoke("Restart", 1) in if; delay 1 second to run Restart Switch scenes
and continue to add GetComponent<AudioSource>().enabled = false; turn off the music

 

15. Make scene transitions

*Create the code EnterHouse using SceneManagement
*Write the code if statement in update when pressing e when scenManager.LoadScene(SceneManager.GetActiveScene().buildIndex +1) Current scene number +1
*Open File Build Settings and drag the scene into the observable number 
*Drag the code and add it to the dialog of enter.
Similarly, write the code to return to scene 1 for scene 2

eb3f4f51c50449ed9f952e49cdfe6bf9.png

 

16. Parallax Parallax

*Create a new Area, copy the background polygon collider to the Area, delete the background collider, and reset the camera. Create a
new code Parallax
*Write code to add variables float MoveRate (adjustment range) float StartPoint (determine the initial position) transform Camera (adjust the position)
* Write code Start to get StartPoint = transform.posion.x
*add y-axis variable  
*add bool variable lockY
*update add if if lockY then run the previous code else y-axis = initial coordinate y + camera movement * magnitude
* will not want up and down Check the lockY of the moving object

423ef54308874fb3af195f4ccedb4cbd.png

 

17. Create the menu

*Create a new scene Menu
*Add UI Panel and change it to black Change Source Image (original image) to null
*Add Panel control color and change Scource Add component Button Text Mesh... Add button
*Adjust button size text color
*write Code Menu Directly create the function PlayGame() SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1); *
Add the function QuitGame() Application.Quit();
*Add the code to the parent class of the button In the button's On Click the component to select the parent class and select the PlayGame function to run the game at this time, click the button to enter

7c7bc3360f03499bad5c080577c3f9d5.png

 6b1969fb784245ab9c7ef0b37e26ebbd.png

 

18. Make the audio track

*Assets creates a new Audio Mixer named MainMixer, finds AudioMixer in Window Audio, and opens the menu
*Select Output for bgm, select master, change the right button of the volume of Attenuation in the Inspector of the master to editable expose,
adjust the audio track in the Menu, and set the minimum value to -80 Maximum value 0
* Write code to create a new variable public AudioMixer AudioMixer in the Menu Drag the component into
* Write code to create a new function public void SetVolume (float value) AudioMixer.SetFloat("The name of the editable code just changed", float value );
* Add code for the track bar Use the SetVolume function to select the above
* Add master for all sound effects to change the volume together

6c8604a710324b659d00e405e528e16a.png

 

19. Pack the game

In Build settings, select Player Settings in the lower left corner, set the parameters you want, return, click build in the lower right corner to package the game.
7516bdf178e14706a41ca11cf06cd1ac.png

 

(4) Common problems and solutions

1.提示unable to access unity services. please log in or request membership to this project

Solution: ①Click "Window" - "General" - "Service" (or direct shortcut key ctrl + 0) ②Click "new link" - choose your own Project ID - click "create".

2.Unity报错:The variable ... has not been assigned.

Solution: Add a rigid body component to the object.

3.提示UnassignedReferenceException: The variable target of Moving has not been assigned.You probably need to assign the target variable of the Moving script in theinspector.Moving.Update () (at Assets/_Tutorial/Moving.cs:13)

Solution: Pull the object into the tagger for setting.


(5) Thanks

1. Thanks to my Unity enlightenment teacher, Mr. Maikou, @M_STDIO
2. The materials used in the game are all from the Unity store
3. Welcome to exchange and learn together, if you have any questions, please private message me [email protected].

 

 

Guess you like

Origin blog.csdn.net/weixin_61056520/article/details/126428530