UnetTank

作者: 玄策丶 | 来源:发表于2019-07-10 15:09 被阅读0次

一、TankCtrl

using UnityEngine;
using System.Collections;
using UnityEngine.Networking;
public class TankCtrl : NetworkBehaviour 
{
    public GameObject Bulletprefab;
    public Transform TrBullet;
    void Start ()
    {
        
    }//end_Start
    
    void Update ()
    {
        if (!isLocalPlayer)
        {
            return;
        }
        float hor = Input.GetAxis("Horizontal1");
        float ver = Input.GetAxis("Vertical1");
        transform.Translate(0, 0, ver * Time.deltaTime * 10);
        transform.Rotate(0, hor * Time.deltaTime * 100,0);
        if (Input.GetKeyDown(KeyCode.Space))
        {
            CmdShoot();
        }
    }//end_Update
    [Command]
    void CmdShoot()
    {
        GameObject tempB = Instantiate(Bulletprefab, TrBullet.position, TrBullet.rotation) as GameObject;
        if (tempB.GetComponent<Rigidbody>())
        {
            tempB.GetComponent<Rigidbody>().velocity = TrBullet.forward * 50;
        }
        Destroy(tempB, 1);
        NetworkServer.Spawn(tempB);
    }
}

二、TankHealth

using UnityEngine;
using System.Collections;
using UnityEngine.Networking;
public class Health : NetworkBehaviour 
{
    public const int MAXHP = 100;
    private int NowHp = MAXHP;
    private NetworkStartPosition[] RespawnerPoints;

    void Start ()
    {
        if (isLocalPlayer)
        {
            RespawnerPoints = FindObjectsOfType<NetworkStartPosition>();
        }
    }//end_Start
    
    void Update ()
    {
        print(NowHp);
    }//end_Update
    public void OnHurt(int hurt)
    {
        if (!isServer)
        {
            return;
        }
        NowHp -= hurt;
        if (NowHp<=0)
        {
            NowHp = MAXHP;
            RpcSpawner();
        }
    }
    [ClientRpc]
    void RpcSpawner()
    {
        if (!isLocalPlayer)
        {
            return;
        }
        Vector3 rePos = Vector3.zero;
        if (RespawnerPoints.Length>0)
        {
            rePos = RespawnerPoints[Random.Range(0, RespawnerPoints.Length)].transform.position;
        }
        transform.position = rePos;
    }
}

Commands命令是由客户端(或具有客户端权限的其他GameObject)发送到服务端,并在服务端运行
ClientRpc命令是由服务端发送到连接到服务端的每一个客户端并在客户端运行

三、Bullet

using UnityEngine;
using System.Collections;
public class Bullet : MonoBehaviour 
{
    private void OnCollisionEnter(Collision collision)
    {
        Destroy(this.gameObject);
        collision.gameObject.GetComponent<Health>().OnHurt(10);
    }
}

相关文章

  • UnetTank

    一、TankCtrl 二、TankHealth Commands命令是由客户端(或具有客户端权限的其他GameOb...

网友评论

      本文标题:UnetTank

      本文链接:https://www.haomeiwen.com/subject/wzjhkctx.html