一、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);
}
}
网友评论