Use multiplayer networking to do a simple multiplayer example -2/3 (Unity3d development 26)

Source: Internet
Author: User

Monkey original, welcome reprint. Reproduced please specify: Reproduced from COCOS2DER-CSDN, thank you!
Original address: http://blog.csdn.net/cocos2der/article/details/51007512

Use multiplayer networking as an example of a simple multiplayer game -1/3
Use multiplayer networking as an example of a simple multiplayer game -2/3
Use multiplayer networking as an example of a simple multiplayer game -3/3

7. Controlling player movement in the network

In the previous article, the player action move will simultaneously control all the player in the same screen, and only their own screen to take effect. Because we haven't synced the transform information yet.
Below we use the Unityengine.networking component to achieve player control of each player

    • Open Playercontroller Script
    • Add namespace Unityengine.networking
using UnityEngine.Networking;
    • Modify Monobehaviour to Networkbehaviour
publicclass PlayerController : NetworkBehaviour
    • Add the following method to the update function
if (!isLocalPlayer){    return;}

Finally, your Playercontroller content is as follows:

using  unityengine; using  unityengine.networking; public  class  playercontroller:networkbehaviour{void  Update () {if  (!islocalplayer) {return ; } var  x = Input.getaxis ( "horizontal" ) * Time.del Tatime * 150.0  F; var  z = input.getaxis ( "Vertical" ) * Time.deltatime * 3.0  F; Transform. Rotate (0 , X, 0 ); Transform. Translate (0 , 0 , z); }}
    • Save Script
    • Back in Unity
    • Select the player prefab in the project panel
    • Keep Player Prefab selected
    • Add Components network > Networktransform
    • Save Project

Networktransform is used to synchronize all client information in the network. Plus islocalplayer judgment, only the current client operation is allowed.

8. Test multi-player movement in the network
    • Same build a Mac standalone application run as host
    • Click LAN Host to start the game as a host
    • Run unity, click LAN Client to join the game as another client
    • Click on the respective WASD to move the respective player
9. Differentiate the respective player

The top two player looks the same, we modify the color of our player

    • Open Playercontroller Script
    • Add Onstartlocalplayer method
publicoverridevoidOnStartLocalPlayer(){    GetComponent<MeshRenderer>().material.color = Color.blue;}

Final Playercontroller:

usingUnityengine;usingunityengine.networking; Public classplayercontroller:networkbehaviour{voidUpdate () {if(!islocalplayer) {return; }varx = Input.getaxis ("Horizontal") * Time.deltatime *150.0Fvarz = Input.getaxis ("Vertical") * Time.deltatime *3.0F Transform. Rotate (0X0); Transform. Translate (0,0, z); } Public Override void Onstartlocalplayer() {getcomponent<meshrenderer> (). Material.color = Color.Blue; }}
    • Build a new Mac version, test the effect
    • Turn off Mac version, stop running unity, go back to edit state
10. Add shooting weapon to player

Create Bullets

    • Create a Sphere Gameobject
    • Modify the name to "Bullet"
    • Select the Bullet object
    • Modify transform (0.2, 0.2, 0.2)
    • Add Components Physics > Rigidbody
    • Cancel the use Gravity in the Rigidbody property
    • Drag-and-drop bullet to the project panel to create a prefab
    • Delete Bullet in scene
    • Save scene

Modify Playercontroller to add fired bullets below

    • Open Playercontroller Script
    • Add Public variable Bulletprefab
public GameObject bulletPrefab;
    • Add Bullet Local Launch point
public Transform bulletSpawn;
    • Adding an input source to the update
if (Input.GetKeyDown(KeyCode.Space)){    Fire();}
    • Add Fire method
void Fire(){    // Create the Bullet from the Bullet Prefab    var bullet = (GameObject)Instantiate (        bulletPrefab,        bulletSpawn.position,        bulletSpawn.rotation);    Add velocity to the bullet    bullet.GetComponent<Rigidbody>().velocity = bullet.transform.forward6;    2 seconds    2.0f);}

The final playercontroller are as follows:

usingUnityengine;usingunityengine.networking; Public classplayercontroller:networkbehaviour{ PublicGameobject Bulletprefab; PublicTransform Bulletspawn;voidUpdate () {if(!islocalplayer) {return; }varx = Input.getaxis ("Horizontal") * Time.deltatime *150.0Fvarz = Input.getaxis ("Vertical") * Time.deltatime *3.0F Transform. Rotate (0X0); Transform. Translate (0,0, z);if(Input.getkeydown (Keycode.space))        {Fire (); }    }voidFire () {//Create the Bullet from the Bullet Prefab        varBullet = (gameobject) instantiate (Bulletprefab, Bulletspawn.position, Bulletspawn.rotatio n);//ADD velocity to the bulletBullet. Getcomponent<rigidbody> (). Velocity = Bullet.transform.forward *6;//Destroy the bullet after 2 secondsDestroy (Bullet,2.0f); } Public Override void Onstartlocalplayer() {getcomponent<meshrenderer> (). Material.color = Color.Blue; }}
    • Save Script
    • Back to Unity

The following is the beginning of modifying the player Prefab for a changed Playercontroller

    • Drag the player prefab to the scene
    • Keep Player Prefab selected
    • Create a cylinder cylinder as its child
    • Modify cylinder name called "Gun"
    • Keep the gun selected
    • Removing capsule collider components
    • Set Transform Position (0.5, 0.0, 0.5)
    • Set transform Rotation (90.0, 0.0, 0.0)
    • Set transform scale (0.25, 0.5, 0.25)
    • Set Material to Black Material

Last player effect:

    • Keep Player selected
    • Create an empty gameobject as a child
    • Modify the empty gameobject name called "Bullet Spawn"
    • Set Bullet Spawn Position (0.5, 0.0, 1.0)

is to set the bullet launch point bullet spawn at the muzzle.

    • Keep Player Prefab selected
    • Drag the bullet Prefab to the bullet Prefab box in Playercontroller
    • Drag the player's child Bullet Spawn to the Bullet Spawn box in Playercontroller
    • Save Project
    • Build a new Mac version, and test

You will find that the spacebar can fire bullets in the respective scene, but bullets do not appear in the other scene.

    • Turn off Mac Version
    • Stop unity and go back to edit mode
11. Increase multi-person shooting

Below we will register bullet prefab to NetworkManager

    • Select Bullet Prefab in the project panel
    • Save Bullet Prefab selected
    • Add Components network > Networkidentity
    • Add Components network > Networktransform
    • Set networktransform in network Send rate to 0

Bullets don't change direction halfway, so we don't need to update each frame, and each client calculates bullet coordinate information by itself, so set the network Send rate to 0 and the networks don't need to synchronize the coordinate information.

    • Select NetworkManager in the hierarchy panel
    • Keep NetworkManager selected
    • Expand Spawn Info
    • Click Registered spawnable prefabs lower right corner +
    • Add bullet prefab to registered spawnable prefabs

    • Open Playercontroller Script

Note [Command] can declare that a function can be called by this client, but it is executed on the server side (host).

    • Add [Command] to fire function
    • Change fire function name to "Cmdfire"
[Command]CmdFire()
    • The update function modifies the call to Cmdfire
CmdFire();
    • Add the Networkserver.spawn method to the Cmdfire function to create the bullet
NetworkServer.Spawn(bullet);

The final playercontroller are as follows:

usingUnityengine;usingunityengine.networking; Public classplayercontroller:networkbehaviour{ PublicGameobject Bulletprefab; PublicTransform Bulletspawn;voidUpdate () {if(!islocalplayer) {return; }varx = Input.getaxis ("Horizontal") * Time.deltatime *150.0Fvarz = Input.getaxis ("Vertical") * Time.deltatime *3.0F Transform. Rotate (0X0); Transform. Translate (0,0, z);if(Input.getkeydown (Keycode.space))        {Cmdfire (); }    }//This [Command] code was called on the Client ...    //... but it's run on the server![Command]voidCmdfire () {//Create the Bullet from the Bullet Prefab        varBullet = (gameobject) instantiate (Bulletprefab, Bulletspawn.position, Bulletspawn.rotatio n);//ADD velocity to the bulletBullet. Getcomponent<rigidbody> (). Velocity = Bullet.transform.forward *6;//Spawn The bullet on the clientsNetworkserver.spawn (bullet);//Destroy the bullet after 2 secondsDestroy (Bullet,2.0f); } Public Override void Onstartlocalplayer() {getcomponent<meshrenderer> (). Material.color = Color.Blue; }}
    • Save Script
    • Back to Unity
    • Build new version of Mac, test

You should see the bullets synced to each player scene.

    • Turn off Mac Version
    • Stop running unity and go back to edit mode
Add player Health Value
    • Add a new script "Bullet" to Bullet Prefab
    • Open Bullet Script
    • Add Collision function
using UnityEngine;using System.Collections;publicclass Bullet : MonoBehaviour {    void OnCollisionEnter(Collision collision)    {        Destroy(gameObject);    }}

The bullet is automatically destroyed after it collides with the player.

Add player Health value
-Add a new script to player Prefab "health"
The health script is as follows:

using UnityEngine;publicclass Health : MonoBehaviour {    publicconstint100;    publicint currentHealth = maxHealth;   publicvoidTakeDamage(int amount)    {        currentHealth -= amount;        if0)        {            0;            Debug.Log("Dead!");        }    }}
    • Save Script

Increased hit injury in bullet

    • Modifying the Oncollisionenter function in bullet
using UnityEngine;using System.Collections;publicclass Bullet : MonoBehaviour {    void OnCollisionEnter(Collision collision)    {        var hit = collision.gameObject;        var health = hit.GetComponent<Health>();        if (health  null)        {            health.TakeDamage(10);        }        Destroy(gameObject);    }}

Add a simple player head blood bar

    • Create a UI Image in the farm
    • Modify the canvas name as "Healthbar Canvas"
    • Modify the image name as "Background"
    • Save Background selected
    • Setting Recttransform Width 100
    • Setting Recttransform Height 10
    • Modify the source Image to built-in Inputfieldbackground
    • Modify Image color to red
    • Do not modify the center point and Anchor Point of the background
    • Copying a copy of background
    • Modify the copied background name called foreground
    • Set foreground to background child
    • Drag the player prefab to the scene
    • Drag the Healthbar canvas into the player as a child
      The entire player structure is as follows:

    • Select foreground

    • Set foreground image to green
    • Modify the foreground center point and anchor point to middle left (for the blood bar to be filled in from leave to right)

    • Select Healthbar Canvas

    • Click Reset in the Recttransform Settings button (pinion)
    • Set Recttransform scale (0.01, 0.01, 0.01)
    • Set Recttransform Position (0.0, 1.5, 0.0)
    • Select Player, click Apply, save player Prefab
    • Save scene

Modify the health script to control the blood bar
The final health script is as follows:

usingUnityengine;usingUnityengine.ui;usingSystem.Collections; Public classHealth:monobehaviour { Public Const intMaxHealth = -; Public intCurrenthealth = MaxHealth; PublicRecttransform Healthbar; Public void Takedamage(intAmount) {currenthealth-= amount;if(Currenthealth <=0) {Currenthealth =0; Debug.Log ("dead!"); } Healthbar.sizedelta =NewVector2 (Currenthealth, HEALTHBAR.SIZEDELTA.Y); }}
    • Save Script
    • Back to Unity
    • Keep Player selected
    • Drag the foreground into the Healthbar input box
    • Apply Player Prefab
    • Delete a player in a scene
    • Save scene

Finally, modify the Healthbar forever toward the main camera
-Add a new script "Billboard" to Healthbar canvas in player prefab
The Billboard script is as follows:

using UnityEngine;using System.Collections;publicclass Billboard : MonoBehaviour {    void Update () {        transform.LookAt(Camera.main.transform);    }}
    • Compiling a new Mac version, testing

You will find that the blood bar has changed only locally, not synced to all players.

Use multiplayer networking to do a simple multiplayer example -2/3 (Unity3d development 26)

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.