Two ways to add an object
Save the scene
1. Click File→Save Scene in the menu at the top of the window.
2. Once saved, the GameScene item is added to the project view (try clicking the Assets TAB on the left if you can’t see it).
Adjust the camera
- Hold down Alt and drag the left mouse button to rotate the camera around the ground.
- Hold down Alt and Ctrl while dragging the left mouse button, and the camera moves in parallel.
- Roll the mouse wheel and the picture moves back and forth toward the depths of the scene.
amplification
After the Cube is selected in the hierarchy view, move the mouse over to the Scene view and then press F (double click) to see the camera move towards the Cube.
Physics engine
To make the player character jump, add physical motion components to the game object.
Select Player in the hierarchy view and click Component→Physics→Rigidbody from the menu at the top of the window.
The Rigidbody component is then added to the player character and can be seen in the inspector.
Run the game again (step 7), this time the player character will fall quickly and stop when it hits the ground.
Make the player character jump (add script)
1. The script is named Player because it is used to manipulate the Player character.
Select C# Script from the Create menu in the project view. In the Assets bar on the right side of the project view a Script file will be generated called NewBehaviourScript. When you’ve just created it change its name to Player.
The script now created is an empty script, and nothing happens if it is run. In order to be able to use it in a game, it must be edited accordingly.
2. Select the Player script and click the Open button in the inspector. Visual Studio 2013 will launch and the player. cs script will open (I changed the Mono Develop editor to VS2013).
Note: Double-click the script item in the project view to also launch the editor (in this case, VS2013).
As you can see, the script file you created already contains several lines of code. This code is required for every script, so it is pre-set in the file to save typing.
3. Script editing
(1) There is a line of code at the beginning of the script to confirm that the public class followed by the class name Player (Unity specifies that the class name must be the same as the folder name).
(2) Code editing scripts
- Add a jump_speed data member
- Override the Update method
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour {
protected float jump_speed = 5.0 f; // Set the takeoff speed
// Use this for initialization
void Start (){}// Update is called once per frame
void Update () {
if (Input.GetMouseButtonDown(0)) // Click the left mouse button to trigger
{
this.GetComponent<Rigidbody>().velocity = Vector3.up * this.jump_speed; // Set the upward speed}}}Copy the code
5. Add the new class component to the Player game object.
Drag the Player script from the project view onto the Player object in the hierarchy view. This allows you to add the Player script component to the Player character, and the Player tag should also be visible in the inspector.
6. Start the game again. Click the left mouse button and the character pops up (save the project file again before running). If you can’t jump, check to see if the rigidBody component is not added
Create the material
1. Create the material
(1) In the project view, click Create→Material to Create a New Material item. Just like the script, change its name to Player Material.
(2) Change the color
Click the white rectangle in the inspector to open the Color selection window titled Color.
There is a color palette on the right side of the color selection window. Click on the red area, and the white rectangle will be displayed as the selected color immediately. Close the selection window after selecting the color.
2. In the project view, drag the Player Material onto the Player in the hierarchy view. This is equivalent to assigning the Player Material to the Player, and the game object Player in the scene view becomes red.
3. Create a green Ball Material and a blue Floor Material in the same way and assign them to the Ball and Floor objects, respectively.
Resize the game screen (adjust player Settings)
1. There is Free Aspect text at the lower left of the Game label. Click it and a drop-down menu will appear.
2. Enter 640 and 480 in the text boxes to the right of the Width&Height text and press the OK button.
3. After closing the Add window, you can see that 640 is added in the drop-down menu480 items, and the left side of the item shows the selected mark. So far, we’ve managed to set the screen size of the game to 640480 pixels.
4. Run the game (save before running)
Physical motion and speed
While the ball is still in the air, let’s try to make it fly towards the player character.
In order for the ball to simulate physical motion, the Rigidbody component needs to be added. You also need to create a script for the Ball. This is done in steps 10 and 11 in the Unity Starter tutorial (part 1).
After adding the Ball script, we will make the following changes to the Start method
void Start () {
this.GetComponent<Rigidbody>().velocity = new Vector3(8.0 f.8.0 f.0.0 f); // Set the speed to the upper left
}
Copy the code
When the game starts, the ball flies to the left of the screen
Preset game resources
In order to be able to create a ball object at any time, the ball object needs to be preset first.
1. Drag and drop the Ball item text from the hierarchy view into the project view
The Ball item appears in the project view. At the same time, the text of the Ball item in the hierarchy view will turn blue.
2. Drag the Ball default from the project view into the scene view
You can see that there is an extra ball object in the scene.
Once the game object is preset, it’s easy to create multiple identical objects.
3. Make Player and Floor game objects default as well
Organize the project view
1. Organize these projects in folders
After clicking Create→Folder in the menu in the upper left corner of the project view, a Folder will be generated in the project view, changing the name to Prefabs.
2. Drag the preset Ball Prefab into the Prefabs folder
Click on the Prefabs folder to see the Ball preset you just moved. Then move the Player and Floor presets to the Prefabs folder as well.
Create Scenes, Scripts, Materials folders in the same way and put each project in its own folder
Note that you must click the Assets icon on the left side of the project view to ensure that the current folder goes back to Assets before creating it.
Gameobjects are created by scripting
(1) Switch to the Prefabs folder in the project view and select the Launcher Preset. The inspector displays information about the Launcher, and click the Add Component button at the bottom
(2) In the drop-down menu titled Component, click the Script item at the bottom. Click and the menu moves to the left, showing all the scripts you’ve created. Find the Launcher script and click.
Summary: Now that we know you can add components in the inspector, you can also use the top of the window menu or drag and drop.
5. Edit the Launcher script
In addition to the Update method changes, the ballPrefab variable has been added.
Instantiate is a method of generating instances of game objects by default. However, there is no code in the script to initialize the ballPrefab variable, so it must be assigned a preset object value in the inspector before the game can run.
public class Launcher : MonoBehaviour {
public GameObject ballPrefab; // Small ball preset
// Use this for initialization
void Start (){}// Update is called once per frame
void Update () {
if (Input.GetMouseButtonDown(1)) // Click the right mouse button to trigger
{
Instantiate(this.ballPrefab); // Create an instance of ballPrefab}}}Copy the code
Select the Launcher preset from the project view. You can see the Ball Prefab entry displayed under the Launcher (Script) TAB in the inspector. All public member variables declared in the script code will be listed here.
A new variable added to the class defaults to None (GameObject), which means that the variable has not been assigned a value. Please drag the Ball preset from the project view here (hold the left mouse button down and do not let go).
6. Run the game
Every time you click the right mouse button, a small ball is shot out.
Here, to separate the default objects from the Instantiate methods in the script, we call the game objects generated by the Instantiate method instances and the process of generating the instance instantiation.
Remove game objects by scripting
We now have a Bug in the game: pellets that are launched never disappear.
Gameobjects dynamically generated by the script while the game is running are also displayed on the hierarchy map. Each mouse click adds a Ball (Clone) gameobject to the hierarchy view. So even when the balls are out of the game screen, the game objects don’t disappear.
Balls that run out of the screen do not return to the screen, so you can remove them completely.
Add the OnBecameInvisible method to the script ball. cs, which can be added anywhere within the scope of the Ball class definition.
public class Ball : MonoBehaviour {
// Add: method to be called when the gameobject runs out of screen
void OnBecameInvisible()
{
Destroy(this.gameObject); // Delete the gameobject
}
// Use this for initialization
void Start () {
this.GetComponent<Rigidbody>().velocity = new Vector3(8.0 f.8.0 f.0.0 f); // Set the speed to the upper left
}
// Update is called once per frame
void Update (){}}Copy the code
OnBecameInvisible is a method that is called when a game object has moved out of the frame and is no longer being drawn.
Destroy(this.GameObject) is the method that destroys the gameObject.
Note: If you set the parameter to this, instead of removing the gameobject, you remove the Ball script component.
Handling in case of collision
To prevent the player character from jumping in the air again, let’s add the following handle
- Add landing mark
- Take-off is not allowed when the landing mark value is false
- Set the landing mark at the moment of take-off to false
- Set the landing flag at the moment of landing to true
Add the Tag to the project, select Floor Default in the project view → Click Untagged→ Click Add Tag→ click the triangle to the left of Tags → click “+” → Enter Floor→ Select Floor default in the project view again → click Untagged→ Click Floor
Modify the Player script as follows:
public class Player : MonoBehaviour {
protected float jump_speed = 8.0 f; // Set the takeoff speed
public bool is_landing = false; // Landing mark
// Use this for initialization
void Start () {
this.is_landing = false;
}
// Update is called once per frame
void Update () {
if(this.is_landing){ // Triggered after landing
if(Input.GetMouseButtonDown(0)) {if (this.is_landing)
{
this.GetComponent<Rigidbody>().velocity = Vector3.up * this.jump_speed; // Set the upward speed
}
this.is_landing = false; // Set the landing flag to false (not landing = in the air)}}}// Add: method to be called when a collision occurs with another gameobject
void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.tag == "Floor")
{
this.is_landing = true; // Set the landing flag to true (landing = on the ground)}}}Copy the code
The OnCollisionEnter method is called when a gameobject collids with another object.
This is added to check if the player character has landed. Set the value of the landing flag to true in this method. The player character cannot jump again in the air.
Inhibition of rotation
With the scripting of the player character and the ball to some extent completed, let’s adjust the parameters so that the character can collide with the ball after the jump.
Here we use the following values:
- Player character position :(-2.0,1.0,0.0)
- The jump speed of the Player character (jump_speed in player. cs script) : 8.0
- Ball position :(5.0,2.0,0.0)
- Initial Ball speed (set using the Start method in the ball-.cs script) :(-7.0,6.0,0.0)
1, select Player in the project view and open the Constraints item under the Rigidbody tag in the inspector
2. Click the triangle icon on the left to further display Freeze Position and Freeze Rotation
Freeze Position is used to fix the Position coordinates of the gameobject in certain directions, and Freeze Rotation is used to fix the Angle.
Since we want the player character to only jump up and down and not move side to side or back and forth:
3. Select X and Z in the Freeze Position. To Freeze Rotation, select “X”, “Y”, and “Z”
Set up the weight
Select the Ball default in the project view, open the Rigidbody TAB, and change the value of the Mass item from 1 to 0.01.
The Mass item is used to set the weight of the game object. When two game objects collide, the object with a large Mass will continue to move at its original speed, while the object with a small Mass will easily change the direction of movement due to the impact.