Unity3D game development from zero to single (7), unity3d Game Development

Source: Internet
Author: User
Tags dota

Unity3D game development from zero to single (7), unity3d Game Development
Abstract

Today, I made a network communication demo for a mobile device, which consists of two parts: network connection and data communication.

Two Android devices A and B are required. A serves as the client and B serves as the server.

The final effect is that the square in device A is controlled by the player, and the square in Device B is also started, and the information of the accelerator sensor in device A is also updated in real time in Device B.



Network Connection

First, the two devices need to be connected to the Internet, and the IP address is in the same network segment, for example, connected to the same route, or sent a Wi-Fi signal through the notebook, and then connected to the device.

Create a new project in Unity3d, and create two empty objects, one Client and one Server in the scene.

Create a script client. cs in the client

using UnityEngine;using System.Collections;public class client : MonoBehaviour {    private string IP = "10.66.208.191";    private string clientIp;    private string clientIpSplite;    private Vector3 acceleration;    public GameObject cube;    private bool cubeInitialed = false;    //Connet port     private int Port = 10000;    void Awake()    {        clientIp = Network.player.ipAddress;        string[] tmpArray = clientIp.Split('.');        clientIpSplite = tmpArray[0] + "." + tmpArray[1] + "." + tmpArray[2] + ".";    }        void OnGUI()    {        switch (Network.peerType)        {            case NetworkPeerType.Disconnected:                StartConnect();                break;            case NetworkPeerType.Server:                break;            case NetworkPeerType.Client:                OnConnect();                break;            case NetworkPeerType.Connecting:                break;        }    }    void StartConnect()    {        if (GUILayout.Button("Connect Server"))        {            NetworkConnectionError error = Network.Connect(IP, Port);            Debug.Log("connect status:" + error);               }    }    void OnConnect()    {        if(!cubeInitialed)        {            Network.Instantiate(cube, transform.position, transform.rotation, 0);            cubeInitialed = true;        }    }}


The client performs the corresponding action based on the current status. StartConnect is responsible for the connection.

Static NetworkConnectionError Connect (string [] IPs, int remotePort)

The first parameter is Ip, and the second parameter is port.


After the connection, call the OnConnect function to initialize a square. Note that this square is initialized on the client and belongs to this client. After it is created, a cube will be instantiated on devices connected to other buckets, but only NetworkView is available on this client. isMine is true.


The following is the server code.

Using UnityEngine; using System. collections; public class server: MonoBehaviour {private int serverPort; public GUIText status; void Awake () {serverPort = 10000 ;}// OnGUI method, all GUI painting needs to implement void OnGUI () {// Network in this method. peerType is the status of the end type: // It can be disconnected, connecting, server or client. peerType) {// disable Client connection. case NetworkPeerType is not initialized on the server. disconnected: StartServer (); break; // run on the server side case NetworkPeerType. server: OnServer (); break; // run on the client case NetworkPeerType. client: break; // attempting to connect to the server case NetworkPeerType. connecting: break;} GUILayout. label (Network. player. ipAddress);} void StartServer () {// true if (GUILayout. button ("create server") {// initialize the local server port. The first parameter is the number of connections received by the local machine. NetworkConnectionError = Network. initializeServer (12, serverPort, false); Debug. log ("error Log" + error) ;}} void OnServer () {GUILayout. label ("the server is running, waiting for client connection"); int length = Network. connections. length; for (int I = 0; I <length; I ++) {GUILayout. label ("client" + I); GUILayout. label ("Client ip" + Network. connections [I]. ipAddress); GUILayout. label ("client port" + Network. connections [I]. port) ;}} void OnSerializeNetworkView (BitStream stream, NetworkMessageInfo info) {// Always send transform (depending on reliability of the network view) if (stream. isWriting) {Vector3 pos = transform. localPosition; Quaternion rot = transform. localRotation; stream. serialize (ref pos); stream. serialize (ref rot);} // When refreshing ing, buffer the information else {// Receive latest state information Vector3 pos = Vector3.zero; Quaternion rot = Quaternion. identity; stream. serialize (ref pos); stream. serialize (ref rot );}}}


After you click Create server on the screen, a server is created on the device to listen to the corresponding port. When other devices are connected, the client information is printed, supports connections from multiple devices.


Create a cube prefab for dynamic creation.



CubeController is used to control the movement of blocks, and NetWorkView is used for data communication.


Data Communication

A NetworkView component must be added to all gameobjects for data communication. There are two methods for data communication: Status synchronization and RPC (Remote process call ). In CubeController. cs, both methods are useful.

using UnityEngine;using System.Collections;public class CubeController : MonoBehaviour {    private GUIText accelText;    void Start()    {        accelText = GameObject.FindGameObjectWithTag("AccelTip").GetComponent<GUIText>() as GUIText;        accelText.text = "";    }    void Update()    {        if(Network.isClient)        {            Vector3 acceleration = Input.acceleration;            accelText.text = "" + acceleration;            networkView.RPC("UpdateAcceleration", RPCMode.Others, acceleration);        }        Vector3 moveDir = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));        Vector3 cubescreenPos =  Camera.main.WorldToScreenPoint(transform.position);        if (Input.GetMouseButton(0))        {            moveDir = new Vector3(Input.mousePosition.x - cubescreenPos.x, Input.mousePosition.y - cubescreenPos.y, 0f).normalized;        }        Debug.Log("moveDir: " + moveDir);        float speed = 5;        transform.Translate(speed * moveDir * Time.deltaTime);    }    void OnSerializeNetworkView(BitStream stream, NetworkMessageInfo info)    {        if (stream.isWriting)        {            Vector3 pos = transform.position;            stream.Serialize(ref pos);        }        else        {            Vector3 receivedPosition = Vector3.zero;            stream.Serialize(ref receivedPosition);            transform.position = receivedPosition;        }    }     [RPC]    void UpdateAcceleration(Vector3 acceleration)    {        accelText.text = "" + acceleration;    }}

Function OnSerializeNetworkView (stream: BitStream, info: NetworkMessageInfo ){}
This is a func provided in Network class. it is mainly responsible for message sent/receive, which will synchronize the objects in the script followed by network view, that is, when you write a script containing OnSerializeNetworkView (){}, if it is thrown to the observed attribute, the code in OnSerializeNetworkView () will start to operate. Basically, he sends and receives information on the network through BitStream objects, and does not need to know the packet problem or how to cut packets. In this demo, the server is only responsible for receiving information, so only the code after else is executed, the client sends information, and the code after if is executed.

Here, the state synchronization of cube selects Unreliable, and the corresponding communication protocol is UDP, which features no connection and is faster.

A typical RPC application scenario is a chat room. It is also very simple to use. First, define an rpc function (add [RPC] above) and call it through NetWork. RPC. Here, the client's gravity sensor data is transmitted and updated on the interface.


Reference

Unity3D network resource allocation & role control-http://ppb440219.blogspot.com/2011/12/unity3d.html

Network View-http://game.ceeger.com/Components/class-NetworkView.html

Remote Procedure Call Details RPC Details-http://game.ceeger.com/Components/net-RPCDetails.html

State Synchronization Detailshttp: // game.ceeger.com/Components/net-StateSynchronization.html

Unity Networking Tutorial-http://www.palladiumgames.net/tutorials/unity-networking-tutorial/





For beginners, click game development. By the way, click unity3D.

If you really want to do this, you have to start from scratch and from the most basic. There are several videos on the Internet that seem good after learning U3D for two months. In fact, they are all plug-ins. This method seems to be fast but basically useless, just to satisfy vanity, what can a scenario without interaction be considered?
I started from scratch, and now it's almost half a year. The most difficult thing I feel is programming, because I have never touched it before, and it's a little basic for Model Materials. Most of the time is spent on learning programming, because this aspect cannot be bypassed. Although there is a plug-in playMaker that can play games without programming experience, it doesn't feel good, but if you don't want to learn programming, you can try it.
For programming, unity often uses Javascript and C #. Although javascript is easy to learn, Unity's javascript is not a standard, but its unique UnityScript, but now there is no systematic UnityScript teaching material, so it is not easy for me to learn. However, I am still reading UnityScript, because I learned it from the beginning and want to learn it and then change it to C #. C # is recommended if you want to learn it, but I don't know if unity's c # is the same as standard c #. You can make a decision in this regard.
If untiy is suitable for personal development, you can watch the video of kotoyev. There is a comparison between unity and several other engines, among which there is a well-known engine such as unreal.
If you say that it has been made in two years, it still feels reliable, but in the first year, you should stick to the foundation. Even if the foundation is ready, do not rush to make large games or try some games.
One of the reasons for using unity is that I have not compiled a map in the Warcraft map editor, but since the editor can make something as classic as dota, can't unity be used? By the way, I know dota but I have never played it. Cheng Hai has been playing it for a while. Compared with dota, I prefer other Warcraft games on the haofang platform, for example, the fire of passers-by in the past, the war of rabbits and sheep, and so on. The Battle of warcraft also has a high level, such as the bloody mission, which can be called the highest in China, while the Open-mode reverse-flow battle can be played as an online game.

In addition, not all things need to be done by yourself. For example, in Outfit7 development, the first model used was bought from a website. If a plug-in is very helpful for game production, you may wish to use it. However, we recommend that you start from the basics and use the plug-in to improve efficiency.
Currently, the active forum in China is the unity holy book.
Other sub-sections, such as tiandihui and cocochina, are not very active and unity3d8 is also good. However, many resources need to be downloaded at a higher level.
It is only a transformation for whether a character is 2D or 3D. The so-called 2D is a series of rendered images. Most of these images are rendered using 3D models, but unity is not suitable for 2D, only plug-ins are available.

Because it is self-taught, there is no systematic thing to tell you, you can only say that this is a very difficult way, do it after making a decision!
It's a bit messy.

Questions about unity3D Game Development

I have been familiar with virtools and unity, and I feel that the engine has its own advantages. As long as I master all of them, I personally feel that unity is in line with my style. Not very gorgeous, but all game functions can be implemented. There are a lot of resources available for download in the unity store, and it is also very convenient to make 2d games.
You can also export your own game to your mobile phone. If you are narcissistic, you will feel satisfied. You can combine art and programming very well. There are very few talents in this field. It is not difficult to learn about unity. As long as you complete several game production examples with video, you can achieve most of the functions. To be proficient, you must study it.
There are many cracked versions of unity on the Internet, and 3.0 is enough. The cracked version is still stable. Occasional problems.
I feel that about 5000 of my laptop can meet the requirements, and I need to use a desktop computer to make a precision model.

Related Article

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.