Unity3D Game Development 12th crazy ball

Source: Internet
Author: User

Next we will use a specific example to learn how to use the physical engine. This instance uses a third-person perspective to control small ball objects in the game, the game uses a collision with a diamond to determine whether to find and earn points. After 10 points are obtained, it wins the game. When the ball hits the runway, the game fails, and prompt whether to start the game again.


Open the folder Assets-> object in sequence, find the Runway. fbx file in the object folder, and drag it into the scenario, for example:


Select the Runway game object, modify the Position (88, 48.5, 57), Rotation (270,350, 0), Scale (, 1) of the Transform component, and select the Main Camera object, modify the Position (88,60, 45), Rotation (55,0, 0), Scale (, 1) of the Transform component, for example:


Next we will add a parallel light source, open GameObject-> Create Other-> Directional light in the menu bar, and modify the Position (, 58), Rotation (48, -), Scale (, 1), for example:


Then we add a Sphere, open the GameObject-> Create Other-> Sphere in the menu bar, name it Ball, set its position (, 48), Rotation (, 0 ), scale (, 1), then open the menu bar Component-> Physics-> Rigidbody, and add a rigid body Component to the Ball object, for example:


Add a material file to the ball, for example:


Now the ball cannot be moved, so we have to bind a script to the ball, create a folder, name it Scripts, create a new C # file in the Scripts folder, and name it BallControl. the code for cs is as follows:

Using UnityEngine; using System. collections; public class BallControl: MonoBehaviour {// speed of ball movement public float movementSpeed = 6.0f; // horizontal movement of the ball private Vector3 horizontalMovement; // private Vector3 verticalMovement; // Use this for initializationvoid Start () {}// Update is called once per framevoid Update () {// Vector3.right x zhouhorizontalMovement = Input. getAxis ("Horizontal") * Vector3.right * movementSpeed; // z zhouverticalMovement = Input. getAxis ("Vertical") * Vector3.forward * movementSpeed; // The ball's motion Vector3 movement = horizontalMovement + verticalMovement; // Add rigidbody to the ball. addForce (movement, ForceMode. force );}}
Then bind it to the Ball object, such:


Click the Play button and we can use the keyboard to control the movement of the ball, for example:

Next, we will add a diamond game object to the Gem. drag the fbx file into the scenario, copy 10 such objects, and name Gem1 -- Gem10 in sequence. Open the menu bar to create an empty game object named Gems, then drag the Gem1-10 into the Gems object, such:


Set the Transform component properties of the Gem1-Gem10 object in sequence, Gem1 Position (78,50, 55), Rotation (-90,0, 0), Scale (0.27, 0.27, 0.27 ), select "Is Trigger" under the Mesh Collider component, set the tag to Pickup, and set the remaining gem objects in sequence, as shown in the following figure:


Modify the BallControl. cs script to make the diamond disappear when the ball is in conflict with the diamond. Add the following code:

Void OnTriggerEnter (Collider other) {// determine whether the ball collides with the diamond object if (other. tag = "Pickup") {// Destroy object Destroy (other. gameObject );}}

Next, we Create a plane. In turn, open the menu bar GameObject-> Create Other-> Cune and name it GameOverTrigger. This object is used to determine whether the ball is in conflict with it. If yes, the ball rushed out of the runway and the game failed. We set the Transform component attributes, Position (90, 40, 55), Rotation (118, 0), Scale (,), such:


Check the Is Trigger check Box under Box Collider, deselect the Mesh Renderer check Box, and create a c # script named GameOverTrigger. cs. The Code Is as follows:

using UnityEngine;using System.Collections;public class GameOverTrigger : MonoBehaviour {    void OnTriggerEnter()    {        Debug.Log("over");    }}

Bind the script to the GameOverTrigger object to preview the game. When the ball leaves the runway, we print over. Next we will create a new script named CrayBallManager. cs to process some logic such as winning or losing scores. The Code is as follows:

Using UnityEngine; using System. collections; // enumerate public enum CrazyBallState {playing, won, lost}; public class CrazyBallManager: MonoBehaviour {// Single Instance public static CrazyBallManager CB; // click public GUIStyle buttonStyle; // tag public GUIStyle labelStyle; // The total number of diamond private int totalGems; // find the number of diamond private int foundGems; // The state of the game private CrazyBallState gameSate; void Awake () {CB = this; foundGems = 0; gameSate = CrazyBallState. playing; totalGems = GameObject. findGameObjectsWithTag ("Pickup "). length; // start the game Time. timeScale = 1.0;} void OnGUI () {GUI. skin. label = labelStyle; GUI. skin. button = buttonStyle; // The number of diamonds found is GUILayout. label ("Found gems:" + foundGems + "/" + totalGems); if (gameSate = CrazyBallState. lost) {// a message indicating a game failure GUILayout is displayed. label ("You Lost"); if (GUI. button (new Rect (Screen. width/2, Screen. height/2,113, 84), "Play again") {// reload the scenario Application. loadLevel (Application. loadedLevel) ;}} else if (gameSate = CrazyBallState. won) {GUILayout. label ("You won"); if (GUI. button (new Rect (Screen. width/2, Screen. height/2,113, 84), "Play again") {// reload the scenario Application. loadLevel (Application. loadedLevel) ;}} public void FoundGem () {foundGems ++; if (foundGems >=totalgems) {WonGame () ;}} public void WonGame () {// pause the game Time. timeScale = 0.0; gameSate = CrazyBallState. won;} public void SetGameOver () {// pause the game Time. timeScale = 0.0; gameSate = CrazyBallState. lost ;}}
In the CrayBallManager script file, the FoundGem () function is called every time and the FoundGems variable is accumulated once. Therefore, we modify the following code in BallControl. cs:

{// Determine whether the ball is in conflict with the diamond object if (other. tag = "Pickup") {CrazyBallManager. CB. foundGem (); // Destroy the object Destroy (other. gameObject );}}

Modify GameOverTrigger. cs as follows:

 void OnTriggerEnter()    {        CrazyBallManager.CB.SetGameOver ();//

Set CrayBallManager. the cs script is bound to the Main Camera object. Then, click the Main Camera object, click the ButtonStyle attribute, set the Background attribute, put it into an image, set FontSize to 18, and Alignment to Middle Center, set Fixed Width to 113 and Height to 84, for example:


Run a game, such:


The camera in the game does not follow the ball, which makes it difficult to operate the game. So I create a script called BallCamera. cs. The Code is as follows:

Using UnityEngine; using System. collections; public class BallCamera: MonoBehaviour {// the following target object public Transform target; // The relative height of the target object public float relativeHeigth = 10.0f; // relative distance from the target object public float zDistance = 5.0f; // damping speed public float dampSpeed = 2; void Update () {Vector3 newPos = target. position + new Vector3 (0, relativeHeigth,-zDistance); // follow the target object transform like a spring. position = Vector3.Lerp (transform. position, newPos, Time. deltaTime * dampSpeed );}}
Bind to the Main Camera object. The target is a ball object and runs the game, for example:







Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.