Unity multiplayer online game (1)

1. Create a NetWorkManager empty object management network

Create a new scene, mount an empty object NetWorkManager under the scene, add NetWorkManager and NetworkManagerHUD components to it

2. Add Player Object

  • Add a Player object and generate it as a prefab Prefab
  • Mount the PlayerController script to control the rotation and movement of the object

3. Realize the synchronization of client and server objects

  • After loading the prefab, it is found that the two players on the server and the client are moving at the same time. Solution: Inherit the playercontroller from NetworkBehaviour, which has an isLocalPlayer property. If it is not a local player, do nothing to return.
  • Synchronize the positions of both sides: mount NetworkTransform in the player to achieve the synchronization function

4. Change the color of local objects

 public override void OnStartLocalPlayer()
    {
        //只在本地对象初始化完成后调用
        GetComponent<MeshRenderer>().material.color = Color.blue;
    }

5. Control the protagonist’s shooting

Press the space bar to fire a bullet

 private void fire()
    {
        GameObject bullet = Instantiate(bulletPrefab, bulletPos);
        bullet.GetComponent<Rigidbody>().velocity = bullet.transform.forward * 10f;
        Destroy(bullet, 2);
    }

6. Bullet synced to the client

  1. First add the bullets that need to be generated in NetWorkManager
    image-20210326120216270
  2. All bullets need to be generated by the server and then synchronized to each client. Add [Command] before the fire method that generates bullets and change the method name to CmdFire(), which means that this method is called on the server side.
  3. Add NetWorkTransform to the bullet object to synchronize the bullet
 [Command]
   private void CmdFire()
   {
       GameObject bullet = Instantiate(bulletPrefab, bulletPos);
       bullet.GetComponent<Rigidbody>().velocity = bullet.transform.forward * 10f;
       Destroy(bullet, 2);


       //同步到各个客户端
       NetworkServer.Spawn(bullet);
   }

7. Add a health bar display to the Player

  1. Create Slider
    image-20210326144916171
  2. Slider's Canvas plus LookAtCamera script to prevent the health bar from rotating with the Player
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class LookAtCamera : MonoBehaviour
{
  

   void Update()
   {
       transform.LookAt(Camera.main.transform);
   }
}
  1. Write Health logic to bind it with slider data
public class Health : MonoBehaviour
{
   // 固定血量
   public int bloodCount = 100;
   public int allBlood = 100;
   public Slider slider;

   public void takeDemage()
   {
       //受到伤害
       if (bloodCount > 0)
       {
           bloodCount -= 10;
           slider.value = bloodCount / (float)allBlood;
       }
   }
}

8. Synchronize health bar and blood volume

The more pitted point is that you will find that after step 7 above, the HP of the server has been dropping, but the HP of the client will either not drop or drop very little. This is because our fire logic is processed by the server. Due to network and transmission problems, the server must execute faster than the client anyway. When the server collides and destroys this object, the client does not have this. The object is gone, so that collision detection cannot be performed in a timely manner and the blood volume is reduced.

Solution: The logic of blood volume reduction also allows it to be processed only on the server side, and the client side also only performs synchronization operations.

public class Health : NetworkBehaviour
{
    // 同步血量
    [SyncVar(hook ="OnChangeHealth")]
    public int bloodCount = 100;
    public int allBlood = 100;
    public Slider slider;

    public void takeDemage()
    {
        if (!isServer) return;
        //受到伤害
        if (bloodCount > 0)
        {
            bloodCount -= 10;
        }
    }

    //检测到SncVar 标准的变量变化后,就会执行 OnChangeHealth 这个方法
    void OnChangeHealth(int health)
    {
        slider.value = bloodCount / (float)allBlood;
    }
}

Guess you like

Origin blog.csdn.net/woshihaizeiwang/article/details/115249370
Recommended