As a beginner unity, write this article as a note, the text will inevitably have omissions, improper point also look correct.
Chapter list: First, download resources from asset store and import two, set camera projection mode (Projection) Three, create background (BackGround) Four, set the Lights (Lighting) v. Create a Player object (player)
One, download the resources from the asset store and import
First we create a new project, then click Window->asset Store, search space shooter, find the following resources:
Click on resources to enter the resource details, click Import to Import.
If you have already downloaded a resource, you can import it in download management (or click on the Assets folder that you downloaded when you create a new project, and the resource will automatically be imported when the new is completed):
Second, set the camera projection mode (Projection)
The example is a two-dimensional game, you can set the camera mode to orthogonal mode (orthographic), so that in the camera's field of view, the game object will not increase with the distance, the game object size will only be affected by the camera size zodiac, the larger the field of view, the smaller the game object, Conversely, the smaller the size of the field, the larger the game object becomes. In this example, the projection mode of the main camera is set to orthogonal mode (orthographic), the Size property is set to 10, the camera rotates 90 pairs around the x-axis, so that the camera is facing the ground:
Iii. creation of the background (BackGround)
First create a quad in hierarchy, rename to background, because the background does not need a collider, so we delete the mesh collider component. Since the camera rotates 90° around the x-axis, in order for the background to be facing the camera, we need to rotate the background around the x-axis 90 °. Looking at the background image, the image size is 1024*2048, in order to maintain the scale of the image, we set the background scale property to X:15,y:30,z:1, and then drag the background image onto the background. Since our camera is an orthographic camera, the size of the game object shows no relation to the object's distance from the camera, and for the next step we set the y-axis of the background position to-10. Then we copy a background, named Background_01, and drag background_01 to background, let Background_01 become a sub-object of background, Reset the Transform property of the background_01 and set the y-axis property of the position to 1, and make a good background as follows:
The properties of the background are as follows:
To allow the background to have a slow scrolling effect, we need to add a script to the background to perform the scrolling of the background. Click to select Background, click Add Component->new Script under Inspector View, enter the script name Bgscroller, edit the script content as follows:
(1), declare two variables of the public type, Scrollspeed: Background picture scrolling speed, tilesizez: scrolling length; Declaring a private variable startposition record the initial position
(2), initialize the value of the StartPosition
(3), the Mathf.repeat function prototype is:
static float mathf.repeat (float t,float length);
The function is similar to the modulo operator (return value =t%length), but you can use a floating-point number to return a value between 0~length. For example t=3,length=2.5, the return value is 0.5,t=5,length=2.5 and the return value is 0.0. Time.time is the time at which the frame starts (read-only), which is the time the game starts to now, in seconds. The first sentence in Update () means that as time.time is incremented, the value of newposition repeats between 0~tilesizez and Vector3.forward is the simple code of Vector3 (0,0,1), which is the z-axis direction, The second sentence means that the component is reciprocating (plus the start offset) along the z-axis between the 0~tilesizez.
Back in the hierarchy view, click Background to open the Inspector View, Setting the values of Scrollspeed and Tilesizez to 0.25 and 30,-0.25 for the background backward (z-axis negative direction) movement, the greater the absolute value, the faster the scrolling speed. 30 represents the height of the background picture, we use background and background_01 stitching together is to let the background in the rolling time is continuous. Run and you can see that the background has been continuously scrolled.
Four, set the Light (Lighting)
In order to make the actual effect better, we need to add additional illumination. In order to achieve the purpose of resource classification, we group the light separately, first to create an empty gameobject, renamed to Lighting, the system by default established directional light renamed to main lights, and dragged to lighting, Then set up two directional light under the lighting, named fill lights and Rim light, adjust the illumination angle and illumination color (can adjust to help understand the light), according to the official settings, Main Light angle is rotation (20,-115,0), Fill light angle is rotation (5,125,0), Rim light angle is rotation ( -15,65,0).
V. Create a Player object (player)
Our game is to drive a spaceship, firing shells to shoot down asteroids and enemy aircraft, if we make a mistake our ship will crash, then such an object should include, the spacecraft body, engine effects, detection collision, ammunition mount point, control spacecraft, let us step by step set up.
(1), we set up an empty Gameobject, put the object in the dot position, renamed to the player, we found the spaceship model under the Models folder Vehicle_playership, drag the model into the player object, prefabs- Find the Spaceship engine special effects Engines_player under the >vfx->engines folder and drag the effects underneath the player so that our spaceship model is built.
(2) Adding rigid components and collision detectors to the spacecraft. After adding the rigid components to the spacecraft, we do not want the spacecraft to fall off the force of gravity, so remove the use gravity option:
After adding a rigid body to add collider components to the spaceship, we can try the capsule collider (Capsule Collider) and the mesh collider (mesh Collider) to see the difference between the two, first we add a capsule collider to the spaceship (Capsule Collider), set the properties of the collider as follows:
The collision boundary of the spacecraft in the scene view is as follows:
As can be seen, the range of the red circle is also the detection range of the capsule collider (Capsule Collider), even though this part does not have a hull. This is the characteristics of the capsule collider: the detection accuracy is not high, the detection range may not match the model, but any shape of the object can use capsule collider, and detection efficiency is high.
Next we remove the capsule collider, add a grid collider (mesh Collider) to the spaceship, click the pinion on the right side of the mesh parameter line, select the collision model Vehicle_playership, tick convex and is Trigger:
It can be seen that the spacecraft's detection range is close to the spacecraft model of many triangular patches, the detection accuracy is very high:
The Mesh collider has high detection accuracy, but it also consumes a lot of performance. There is a compromise approach, is to draw the spacecraft model collision of the general corridor, which can improve the collision detection accuracy, but also reduce performance consumption, the specific method is to click on the mesh parameter line to the right of the small gears, the model is selected as a well-player_ship_collider, You can see that collision detection is a lot leaner (here you can remove the mesh renderer box for the spaceship model, leaving only the collision detection range box):
(3), add weapons to the spacecraft hang at the point. Right-click player->create empty, rename it to Shotspawn, adjust the position of the shotspawn so that it is in the front of the spaceship, so that it shoots from this position when the ship launches the bullet.
(4), the production of bullet preset body. Start by setting up a bullet's default body, as follows:
A. Create an empty game object Gameobject, rename it to Boltenemy, add a rigid body (rigidbody) component to Boltenemy, remove the IS gravity option in the rigid body assembly, and leave the object free of gravity.
b, create a quad under Boltenemy, rename to VFX, find FX_LAZER_ORANGE_DFF under the textures (Textures) folder, drag to FX, and select Shader in particles-> (shader) Additive, this time the VFX plane is parallel to the camera, the camera is unable to display VFX, so you need to rotate the VFX along the X axis 90 degrees:
C, to Boltenemy Add Capsule collider (Capsule Collider), because we only need a collider, so we first delete the VFX object in the mesh Collider, and then add a boltenemy Capsule to Collider, Tick the IS trigger option to edit the detection range of capsule collider, or manually set the range of the collision detection:
Here we set Capsule Collider capsule radius of 0.03, height of 0.5, the direction of Z-axis, after setting the effect as follows:
D, let the bullets move. To get the bullets moving, we need to add a script component to the bullet, click Boltenemy, click Add Component->new Script at the bottom of the Inspector view, enter the name of the scripts mover, complete the creation, for the unified management of resources, We dragged mover to the Scripts folder and edited the mover content as follows:
First, create a public-type variable speed, which makes it easy to modify the velocity value in the Inspector view, creating a rigidbody-type private variable RG, which facilitates access to the object's rigid body components within the class. Assigns a value to the RG object and sets the speed of the rigid body in the start () function, transform.forward the motion direction of the RG object. For the difference between Vector3.forward and Transform.forward, you can refer to http://blog.csdn.net/kaluluosi111/article/details/17206655. Back in the hierarchy view, check Boltenemy set the mover component to speed 20, and run the game to see that Boltenemy is ready to move forward.
E, in the prefabs file add a new Doneprefabs folder, right-click Doneprefabs->create->prefab, create a new Prefab, renamed to Boltenemy, Drag the Boltenemy under the hierarchy view to Boltenemy on the Doneprefabs folder to complete the prefab creation:
You can then delete the Boltenemy in the hierarchy view. If you want to edit prefab again, you can drag and drop the prefab into hierarchy view, edit it and drag it back to prefab to complete the prefab update.
(5), control the spacecraft.
A. Add a controller script to the spacecraft to control the movement of the spacecraft.
Click Player->add component->new Script, enter the name of Playercontroller, edit the script content as follows:
The public variable speed is used to adjust the velocity of the ship's movement in the Inspector View, and the private variable RG is used to access the rigid body components inside the class. Unlike the update () function, the fixedupdate () function is a frame-rate-independent refresh function that is called once at a fixed time interval that can be edit->project settings->time,fixed Timestep parameter setting, default is 0.02s.
The following is excerpted from the Holy Encyclopedia: Input is a system interface that uses this class to read keystrokes set by the input manager and to access multitouch or accelerometer data for mobile devices. To read an axis use the Input.getaxis method to get the following default axes: "Horizontal" and "Vertical" are mapped to the joystick, A, W, S, D, and arrow keys (direction keys). "Mouse X" and "Mouse Y" are mapped to the mouse, "Fire1", "Fire2" "Fire3" are mapped to the keyboard's CTRL, ALT, CMD, and middle mouse buttons or controllers. The new input settings can be added using the input manager. Note: Each input is not updated until "update ()", so it is recommended that you write all of the input calls in the Update method (update loop).
Go back to the Unity Editor, click the Player object, set speed to 10 in the Player controller component, run the game, and you can see that the ship is ready to move.
b, to increase the tilt effect of the spacecraft.
Open the Playercontroller script and edit the following code:
Add the public variable tilt to make it easier to adjust the tilt in the Inspector view. Unity uses a four-dollar number (quaternion) to represent all rotations, and Euler (x, y, z) returns a rotation angle that rotates the Z-degree around the z axis, rotates x degrees around the x-axis, and rotates the Y-degree (in order of this) around the y-axis.
Go back to the Unity Editor, click the Player object, set the tilt to 5 in the Player controller component, run the game, and you can see that the spaceship has a tilt effect when it moves.
C, limit the scope of the ship's movement.
Running the game will find that the spacecraft can move beyond the background, so we have to limit the scope of the ship's movement, by restricting the position properties of the transform component, you can limit the scope of the spacecraft to move. Since our game is a top view, there is no limit to the y-axis, as long as the X and Z axis ranges are limited. Open the Playercontroller script and edit the following code:
First, serialize a class Boundray, instantiate an object Boundray, to limit the range of movement. Clamp (float value,float min,float max) is used to limit value between Min and Max, if value is less than min, returns min, if value is greater than Max, returns MAX, otherwise returns value.
Go back to the Unity Editor, click the Player object, press shortcut W, move the spacecraft to the left and right borders, record the position of the x-axis, move the spacecraft to the upper and lower bounds, record the z-axis position range, and watch the game view to see if the ship has reached the boundary. Fill in the Boundray attribute with the boundary value of the record and run the game to find that the ship has moved within range.
D, let the spaceship fire bullets.
When we press the "Fire1" key, the bullets are fired from the bullet mount point, so the bullets need to be generated dynamically in the script. Open the Playercontroller script and edit the following code:
Gameobject is the base class for all entities in a unity scene and is used here to instantiate bullets. Shotspawn is used to obtain the pose information of a bullet mount point. The firerate is used to set the projectile launch rate. The Nextfire is used to determine whether the next bullet can be launched. When the player presses the "Fire1" key, and the bullet cooldown is reached, a bullet can be fired.
The "Fire1" key is a series of system-defined strings that can be modified by Edit->project Settings->input:
Go back to the Unity Editor, click the Player object, associate the object with the shot and Shotspawn variables, drag the boltenemy to the shot variable, drag shotspawn from the player to the shotspawn variable, Firerate Change to 0.5:
Run the game, press the left mouse button or do the CTRL key, the spaceship has been able to fire bullets.
The next article will make asteroids and enemy aircraft.
Unity-2017.3 Official Example Tutorial Space-shooter (i)