2015年4月16日 星期四

Unity 網路遊戲 功能: 聊天室、看到對方行為

※ 此文章所使用的Unity 版本 Unity 5.0.1,若版本太低請自行改Network語法。

ServerMain (Unity js):

#pragma strict

var Message : String;
var scrollPosistion : Vector2;

function OnGUI ()
{
  if (Network.peerType == NetworkPeerType.Disconnected) {
        GUILayout.Label("Network server is not running.");
        if (GUILayout.Button ("Start Server"))
{
startServer();
}
    }
    else {
    if (Network.peerType == NetworkPeerType.Connecting)
        GUILayout.Label("Network server is starting up...");
    else { 
        GUILayout.Label("Network server is running.");        
        showServerInformation();
        showClientInformation();
        }
        if (GUILayout.Button ("Stop Server"))
{
stopServer();
Message = "";
}
    }
    GUILayout.Box(Message);
}

@RPC
function ReqstMessage(name:String, talkword:String){
Message += "\n" + name + " from :" + talkword;
}

public var listenPort : int;
public var maxClients : int;

function startServer() {
Network.InitializeServer(maxClients, listenPort, false);
}

function stopServer() {
Network.Disconnect();
}

function OnServerInitialized() {
  Debug.Log("Network server initialized and ready");
}

function OnDisconnectedFromServer(info : NetworkDisconnection) {
Debug.Log("Network server disconnected");
}

@script RequireComponent(ServerPlayerManager)
private var spm : ServerPlayerManager;
function Awake() {
spm = gameObject.GetComponent(ServerPlayerManager);
}

function OnPlayerConnected(player: NetworkPlayer) {
Debug.Log("Player " + player + "  connected from ip/port: " + player.ipAddress + "/" + player.port);
spm.spawnPlayer(player);
}

function OnPlayerDisconnected(player : NetworkPlayer) {
Debug.Log("Player disconnected");
spm.deletePlayer(player);
}

function showClientInformation() {
GUILayout.Label("Clients: " + Network.connections.Length + "/" + maxClients);
    for(var p: NetworkPlayer in Network.connections) {
GUILayout.Label(" Player " + p + " from ip/port: " + p.ipAddress + "/" + p.port);
}
}

function showServerInformation() {
GUILayout.Label("IP: " + Network.player.ipAddress + " Port: " + Network.player.port);  
}

ServerPlayerManager (Unity js):

#pragma strict

var players = new Hashtable();

function spawnPlayer(player : NetworkPlayer) {
Debug.Log("Spawning player game object for player " + player);
var ply : PlayerInfo = GameObject.FindObjectOfType(PlayerInfo);
var go : GameObject = Network.Instantiate(ply.playerPrefab, Vector3.up*3, Quaternion.identity, 0);
players[player] = go;
}

function deletePlayer(player : NetworkPlayer) {
Debug.Log("Deleting player game object for player " + player);
  var go : GameObject = players[player];
  Network.RemoveRPCs(go.GetComponent.<NetworkView>().viewID); // remove buffered Instantiate calls
Network.Destroy(go); // destroy the game object on all clienst
players.Remove(player); // remove player from server list
}

@RPC
function handlePlayerInput(player: NetworkPlayer, vertical: float, horizontal: float) {
Debug.Log("Received move from player " + player);
  var go : GameObject = players[player];
  go.transform.position = go.transform.position + Vector3.right*horizontal;
  go.transform.position = go.transform.position + Vector3.forward*vertical;
}


------------------------------------------------------

Client Main(Unity js):

var scrollPosistion : Vector2;

var MyName:String = "";
var Inputword:String = "";
var Outputword:String = "";

function Update() {
if(Input.anyKey) {
sendInputToServer();
}
}

function sendInputToServer() {
var vertical: float = Input.GetAxis("Vertical");
var horizontal: float = Input.GetAxis("Horizontal");
if((vertical!=0)||(horizontal!=0)) {
GetComponent.<NetworkView>().RPC("handlePlayerInput",RPCMode.All,Network.player,vertical, horizontal);
}
}

@RPC
function handlePlayerInput(player: NetworkPlayer, vertical: float, horizontal: float) {          
}

@RPC
function ReqstMessage(sayWord:String,name:String){
Outputword += "\n" + sayWord + " from :" + name;
}
      
function OnGUI ()
{
if (Network.peerType == NetworkPeerType.Disconnected)
{
GUILayout.Label("Not connected to server.");
if (GUILayout.Button ("Connect to server"))
connectToServer();
}
else
{
if(Network.peerType == NetworkPeerType.Connecting)
GUILayout.Label("Connecting to server..."); //unity bug: this never happens
else {
GUILayout.Label("Connected to server.");
GUILayout.Label("IP/port: " + Network.player.ipAddress + "/" + Network.player.port);
}
if(Network.isClient){
scrollPosistion = GUILayout.BeginScrollView(scrollPosistion, GUILayout.Width(200), GUILayout.Height(500));
MyName=GUILayout.TextArea(MyName); 
Inputword=GUILayout.TextArea(Inputword);
GUILayout.Box(Outputword);
if(GUILayout.Button("Enter")){
GetComponent.<NetworkView>().RPC("ReqstMessage", RPCMode.All, Inputword, MyName);
}
}
if (GUILayout.Button ("Disconnect")){
disconnectFromServer();
MyName = "";
Inputword = "";
}
GUILayout.EndScrollView ();
}
}

var remoteIP : String;
var remotePort : int;

function connectToServer() {
Debug.Log("Tyring to connect to Server...");
Network.Connect(remoteIP, remotePort);
}

function disconnectFromServer() {
Debug.Log("Tyring to disconnect from the Server...");
Network.Disconnect();
}

function OnConnectedToServer() {
Debug.Log("Successfully connected to server as player " + Network.player);
}

function OnDisconnectedFromServer (info : NetworkDisconnection) {
  if (info == NetworkDisconnection.LostConnection)
    Debug.Log("Lost connection to the server");
else
Debug.Log("Disconnected from the server");
var gos : GameObject[] = GameObject.FindGameObjectsWithTag("Player");
for(var go : GameObject in gos) {
Destroy(go);
}
}

function OnFailedToConnect (error : NetworkConnectionError)  {
Debug.Log("Failed to connect to Server: " + error);
}

------------------------------------------------------


共用腳本 PlayerInfo(Unity js):

#pragma strict

var playerPrefab : GameObject;

------------------------------------------------------


執行結果:

Server: 

Client  01

Client 02



專案下載: http://pan.baidu.com/s/1mg3Otny


沒有留言:

張貼留言