// ================================================================ // // MonoBehaviour에서 상속. void Start() { this.step = STEP.NONE; this.next_step = STEP.WAIT; GlobalParam.get().fadein_start = true; if (!TitleControl.is_single) { this.m_serverAddress = ""; // 호스트 이름을 얻는다. string hostname = Dns.GetHostName(); // 호스트 이름에서 IP주소를 얻는다. IPAddress[] adrList = Dns.GetHostAddresses(hostname); m_serverAddress = adrList[0].ToString(); GameObject obj = GameObject.Find("Network"); if (obj == null) { obj = new GameObject("Network"); } if (m_network == null) { m_network = obj.AddComponent <Network>(); if (m_network != null) { DontDestroyOnLoad(m_network); } } } }
//=================================================== void Awake() { GameObject netobj = GameObject.Find("Network"); if (netobj != null) { network = netobj.GetComponent <Network>(); } // 로컬 플레이어 생성 createLocalPlayer(GlobalParam.get().global_account_id); Debug.Log("global_account_id" + GlobalParam.get().global_account_id); for (int i = 0; i < GlobalParam.get().playerNum; i++) { // 로컬 플레이어는 스킵 if (i == GlobalParam.get().global_account_id) { continue; } // 연결된 모든 네트워크 플레이어 생성 if (network != null) { createNetPlayer(i); // 생성된 네트워크 플레이어에 인덱스 부여 // 이 인덱스는 노드의 키 값과 같다 GetNetPlayerObject(i).GetComponent <NetPlayerCtrl>().globalId = i; } } }
// ================================================================ // private void SendGameSyncInfo() { Debug.Log("[CLIENT]SendGameSyncInfo"); SyncGameData data = new SyncGameData(); data.version = GameServer.SERVER_VERSION; data.itemNum = 0; // 호스트에서는 이사 정보만 보냅니다. data.moving = new MovingData(); if (GlobalParam.get().local_moving.moving) { data.moving = GlobalParam.get().local_moving; } else { data.moving.characterId = ""; data.moving.houseId = ""; data.moving.moving = false; } SyncGamePacketHouse packet = new SyncGamePacketHouse(data); if (m_network != null) { m_network.SendReliable <SyncGameData>(packet); } }
// 네트 플레이어 만들기. public void createNetPlayer(int account_global_index) { chrBehaviorLocal local_player = this.players[0].GetComponent <chrBehaviorLocal>(); chrBehaviorNet net_player = null; int local_index = this.players.Count; AccountData account_data = AccountManager.get().getAccountData(account_global_index); string avator_name = "Player_" + account_data.avator_id; net_player = CharacterRoot.getInstance().createPlayerAsNet(avator_name).GetComponent <chrBehaviorNet>(); net_player.control.local_index = local_index; net_player.control.global_index = account_global_index; net_player.local_player = local_player; net_player.position_in_formation = this.getInFormationOffset(account_global_index); SHOT_TYPE shot_type = GlobalParam.get().shot_type[account_global_index]; net_player.changeBulletShooter(shot_type); net_player.transform.Translate(this.getLocalPlayer().control.getPosition() + net_player.position_in_formation); this.players.Add(net_player); }
void OnReceiveStartSession(int node, PacketId id, byte[] data) { Debug.Log("ReceiveStartSession"); #if UNUSE_MATCHING_SERVER SessionData response = new SessionData(); { int memberNum = NetConfig.PLAYER_MAX; string hostname = Dns.GetHostName(); IPAddress[] adrList = Dns.GetHostAddresses(hostname); response.endPoints = new EndPointData[memberNum]; response.result = MatchingResult.Success; response.playerId = GlobalParam.get().global_account_id; response.members = memberNum; for (int i = 0; i < memberNum; ++i) { response.endPoints[i] = new EndPointData(); response.endPoints[i].ipAddress = adrList[0].ToString(); response.endPoints[i].port = NetConfig.GAME_PORT; } } #else SessionPacket packet = new SessionPacket(data); SessionData response = packet.GetPacket(); #endif playerId = response.playerId; SetSessionMembers(response.result, response.members, response.endPoints); matchingState = State.MatchingEnded; }
// ---------------------------------------------------------------- // // 패킷 수신 함수]. // 동기 대기 패킷 수신. public void OnReceiveSyncPacket(int node, PacketId id, byte[] data) { Debug.Log("[CLIENT]OnReceiveSyncPacket"); GameSyncPacket packet = new GameSyncPacket(data); GameSyncInfo sync = packet.GetPacket(); GlobalParam.get().seed = sync.seed; // 초기 장비를 보존한다. for (int i = 0; i < sync.items.Length; ++i) { CharEquipment equip = sync.items[i]; GlobalParam.get().shot_type[equip.globalId] = (SHOT_TYPE)equip.shotType; this.select_done_players[equip.globalId] = true; Debug.Log("[CLIENT] AccountID:" + equip.globalId + " ShotType:" + equip.shotType); } // 응답이 있는 쿼리를 검색. string account_id = this.player.control.getAccountID(); QuerySelectFinish query = QueryManager.get().findQuery <QuerySelectFinish>(x => x.account_id == account_id); if (query != null) { Debug.Log("[CLIENT]QuerySelectDone done"); query.set_done(true); query.set_success(true); } Debug.Log("[CLIENT]Recv seed:" + sync.seed); }
// 네트워크 플레이어와 통신이 연결되었는가?. public bool isConnected(int global_account_index) { bool ret = false; if (this.network != null) { int node = this.network.GetClientNode(global_account_index); ret = this.network.IsConnected(node); } else { // 디버그용. if (global_account_index == GlobalParam.get().global_account_id) { ret = true; } else { ret = GlobalParam.get().db_is_connected[global_account_index]; } } return(ret); }
protected Seed create_seed(string id) { string local_account = AccountManager.get().getAccountData(GlobalParam.get().global_account_id).account_id; Seed seed = null; seed = this.seeds.Find(x => x.id == id); if (seed == null) { // 찾지 못했으므로 만든다. seed = new Seed(local_account, id); this.seeds.Add(seed); // [TODO] seeds가 전 단말에서 공통되게 동기화한다. } else { if (seed.creator == local_account) { // 같은 id의 시드를 두 번이상 만들려고 함. Debug.LogError("Seed \"" + id + "\" already exist."); seed = null; } else { // 다른 플레이어가 만든 같은 시드가 있었다. } } return(seed); }
void OnGUI() { // 배경 이미지. if (GlobalParam.getInstance().fadein_start) { float title_alpha = Mathf.InverseLerp(1.0f, 0.0f, this.scene_timer); if (title_alpha > 0.0f) { GUI.color = new Color(1.0f, 1.0f, 1.0f, title_alpha); GUI.DrawTexture(new Rect(0.0f, 0.0f, Screen.width, Screen.height), this.title_image, ScaleMode.ScaleToFit, true); } } if (GlobalParam.get().is_disconnected) { GUI.Button(new Rect(Screen.width - 220.0f, Screen.height - 50.0f, 200.0f, 30.0f), "친구와 연결이 끊어졌습니다"); } else if (GlobalParam.get().is_connected) { if (this.disp_timer > 0.0f) { string message = (GlobalParam.get().account_name == "Toufuya")? "친구가 놀러왔습니다" : "친구와 놀 수 있습니다"; // 대기 중인 플레이어에 게스트가 왔음을 알립니다. GUI.Button(new Rect(Screen.width - 280.0f, Screen.height - 50.0f, 250.0f, 30.0f), message); } } }
// 오류 알림. private void NotifyError() { GUIStyle style = new GUIStyle(GUI.skin.GetStyle("button")); style.normal.textColor = Color.white; style.fontSize = 25; float sx = 450; float sy = 200; float px = Screen.width / 2 - sx * 0.5f; float py = Screen.height / 2 - sy * 0.5f; string message = "통신 오류가 발생했습니다.\n게임을 종료합니다.\n\n버튼을 누르세요."; if (GUI.Button(new Rect(px, py, sx, sy), message, style)) { this.step.set_next(STEP.NONE); if (GlobalParam.get().is_host) { network.StopGameServer(); } network.StopServer(); network.Disconnect(); GameObject.Destroy(network); Application.LoadLevel("TitleScene"); } }
// 오류 GUI private void NotifyError() { GUIStyle style = new GUIStyle(GUI.skin.GetStyle("button")); style.normal.textColor = Color.white; style.fontSize = 20; float sx = 400; float sy = 150; float px = Screen.width / 2 - sx * 0.5f; float py = Screen.height / 2 - sy * 0.5f; string message = "통신 오류가 발생했습니다.\n게임을 종료합니다."; if (GUI.Button(new Rect(px, py, sx, sy), message, style)) { // 네트워크 연결을 끊고 if (GlobalParam.get().is_host) { network.StopGameServer(); } network.StopServer(); network.Disconnect(); hostDisconnected = false; GameObject.Destroy(network); // 타이틀 씬으로 되돌아간다 Application.LoadLevel("UILobby"); } }
// ---------------------------------------------------------------- // // 통신 처리 함수. // public void OnReceiveSyncGamePacket(PacketId id, byte[] data) { Debug.Log("Receive GameSyncPacket.[TitleControl]"); SyncGamePacket packet = new SyncGamePacket(data); SyncGameData sync = packet.GetPacket(); for (int i = 0; i < sync.itemNum; ++i) { string log = "[CLIENT] Sync item pickedup " + "itemId:" + sync.items[i].itemId + " state:" + sync.items[i].state + " ownerId:" + sync.items[i].ownerId; Debug.Log(log); ItemManager.ItemState istate = new ItemManager.ItemState(); // 아이템의 상태를 매니저에 등록. istate.item_id = sync.items[i].itemId; istate.state = (ItemController.State)sync.items[i].state; istate.owner = sync.items[i].ownerId; if (GlobalParam.get().item_table.ContainsKey(istate.item_id)) { GlobalParam.get().item_table.Remove(istate.item_id); } GlobalParam.get().item_table.Add(istate.item_id, istate); } isReceiveSyncGameData = true; }
// 트리거에 충돌한 순간만 호출되는 메소드. void OnTriggerEnter(Collider other) { // 이벤트 박스에 들어간 플레이어를 리스트에 추가한다. do { if (other.tag != "Player") { break; } chrController player = other.gameObject.GetComponent <chrController>(); if (player == null) { break; } if (player.local_index < 0) { break; } if (this.entered_players.Contains(player.local_index)) { break; } this.entered_players.Add(player.local_index); // 게임 서버에 알림. if (this.step.get_current() == STEP.WAIT_ENTER && player.global_index == GlobalParam.get().global_account_id) { CharDoorState door = new CharDoorState(); door.globalId = player.global_index; door.keyId = (this.keyItemName != null)? this.keyItemName : "NONE"; door.isInTrigger = true; door.hasKey = (this.keyItemName != null)? PartyControl.getInstance().hasKey(player.local_index, door.keyId) : true; string log = "DoorId:" + door.keyId + " trigger:" + door.isInTrigger + " hasKey:" + door.hasKey; Debug.Log(log); DoorPacket packet = new DoorPacket(door); if (m_network != null) { int server_node = m_network.GetServerNode(); m_network.SendReliable <CharDoorState>(server_node, packet); } else { PartyControl.get().cmdMoveRoom(door.keyId); } } } while(false); }
// ================================================================ // public ItemState FindItemState(string item_name) { foreach (ItemState state in GlobalParam.get().item_table.Values) { if (item_name.Contains(state.item_id)) { return(state); } } return(default(ItemState)); }
public override void start() { this.next_step = STEP.MOVE; GameObject go = GameObject.Find("Network"); if (go != null) { m_network = go.GetComponent <Network>(); } m_isHost = (GlobalParam.get().global_account_id == 0)? true : false; }
public bool isHost() { bool ret = true; if (network != null) { ret = GlobalParam.get().is_host; } else { return(true); } return(ret); }
// 트리거로부터 뭔가가 부딪힌 순간만 호출되는 메소드. void OnTriggerExit(Collider other) { // 이벤트 박스에서 나온 플레이어를 리스트에서 제거. do { if (other.tag != "Player") { break; } chrController player = other.gameObject.GetComponent <chrController>(); if (player == null) { break; } if (!this.entered_players.Contains(player.local_index)) { break; } this.entered_players.Remove(player.local_index); // 게임 서버에 알림. if (player.global_index == GlobalParam.get().global_account_id) { CharDoorState door = new CharDoorState(); door.globalId = player.global_index; door.keyId = (this.keyItemName != null)? this.keyItemName : "NONE"; door.isInTrigger = false; door.hasKey = PartyControl.getInstance().hasKey(player.local_index, door.keyId); string log = "DoorId:" + door.keyId + " trigger:" + door.isInTrigger + " hasKey:" + door.hasKey; Debug.Log(log); DoorPacket packet = new DoorPacket(door); if (m_network != null) { int serer_node = m_network.GetServerNode(); m_network.SendReliable <CharDoorState>(serer_node, packet); } else { PartyControl.get().clearDoorState(door.keyId); } } } while(false); }
void Fire() { // 발사 된 값을 패킷으로 전달 Vector3 positionData = firePos.position + firePos.right * 0.2f; CharacterCoord packetcoord = new CharacterCoord(positionData.x, positionData.y); float fireForce = GetShotPower(); Quaternion fireAngle = firePos.rotation * Quaternion.Euler(0, 0, v); int characterId = GlobalParam.get().global_account_id; // CharacterRoot에 있는 함수 실행 GameObject.Find("basket").GetComponent <CharacterRoot>().SendAttackCoord(characterId, fireForce, fireAngle, packetcoord); // 프리팹 동적 생성 target_projectile = (GameObject)Instantiate(projectile, positionData, fireAngle); target_projectile.GetComponent <BazookaCtrl>().globalId = GlobalParam.get().global_account_id; }
public void OnReceiveCharacterPacket(PacketId id, byte[] data) { CharacterDataPacket packet = new CharacterDataPacket(data); CharacterData charData = packet.GetPacket(); if (GlobalParam.get().is_in_my_home != GlobalParam.get().is_remote_in_my_home) { return; } chrBehaviorNet remote = CharacterRoot.get().findCharacter <chrBehaviorNet>(charData.characterId); if (remote != null) { remote.CalcCoordinates(charData.index, charData.coordinates); } }
// ================================================================ // public void OnReceiveGoingOutPacket(PacketId id, byte[] data) { GoingOutPacket packet = new GoingOutPacket(data); GoingOutData go = packet.GetPacket(); Debug.Log("OnReceiveGoingOutPacket"); if (GlobalParam.get().account_name == go.characterId) { // 자신은 이미 행동이 끝났으므로 처리하지 않습니다. return; } if (GlobalParam.get().is_in_my_home) { // 자신의 정원에 있습니다.. if (go.goingOut) { // 친구가 찾아왔습니다. this.step.set_next(STEP.WELCOME); GlobalParam.get().is_remote_in_my_home = true; } else { // 친구가 돌아갑니다. this.step.set_next(STEP.BYEBYE); GlobalParam.get().is_remote_in_my_home = false; } } else { // 친구 정원에 있습니다. if (go.goingOut) { // 친구가 갑니다. this.step.set_next(STEP.BYEBYE); GlobalParam.get().is_remote_in_my_home = true; } else { // 친구가 돌아옵니다. this.step.set_next(STEP.WELCOME); GlobalParam.get().is_remote_in_my_home = false; } } }
// ================================================================ // public ItemState FindItemState(string item_name) { foreach (ItemState state in GlobalParam.get().item_table.Values) { if (item_name.Contains(state.item_id)) { return(state); } } ItemState dummy; dummy.item_id = ""; dummy.state = ItemController.State.None; dummy.owner = ""; return(default(ItemState)); }
void OnGUI() { // 배경 이미지 if (GlobalParam.get().fadein_start) { float title_alpha = Mathf.InverseLerp(1.0f, 0.0f, this.scene_timer); if (title_alpha > 0.0f) { GUI.color = new Color(200.0f, 200.0f, title_alpha); GUI.DrawTexture(new Rect(0.0f, 0.0f, Screen.width, Screen.height), this.loading_image, ScaleMode.ScaleToFit, true); } } if (hostDisconnected) { NotifyError(); } }
// 리모트 플레이어를 만든다.. public void createNetPlayers() { Debug.Log("Create Remote players"); for (int i = 0; i < NetConfig.PLAYER_MAX; i++) { // 로컬 플레이어는 스킵. if (i == GlobalParam.get().global_account_id) { continue; } Debug.Log("Create Remote players[" + i + "] " + this.isConnected(i)); if (!this.isConnected(i)) { continue; } if (this.network != null) { PartyControl.get().createNetPlayer(i); } else { PartyControl.get().createFakeNetPlayer(i); } } if (this.network == null) { for (int i = 0; i < PartyControl.get().getFriendCount(); i++) { chrBehaviorFakeNet friend = PartyControl.get().getFriend(i) as chrBehaviorFakeNet; if (friend == null) { continue; } friend.in_formation = true; } } }
public void NotifyFieldMoving() { GameObject go = GameObject.Find("Network"); if (go != null) { Network network = go.GetComponent <Network>(); if (network != null) { GoingOutData data = new GoingOutData(); data.characterId = GlobalParam.get().account_name; data.goingOut = GlobalParam.get().is_in_my_home; GoingOutPacket packet = new GoingOutPacket(data); network.SendReliable <GoingOutData>(packet); } } }
void OnTriggerExit(Collider other) { do { var player = other.gameObject.GetComponent <chrBehaviorLocal>(); if (player == null) { break; } if (!GlobalParam.get().is_in_my_home) { break; } player.onLeaveHouseMoveEventBox(); } while(false); }
public void OnReceiveMovingPacket(PacketId id, byte[] data) { Debug.Log("OnReceiveMovingPacket"); MovingPacket packet = new MovingPacket(data); MovingData moving = packet.GetPacket(); Debug.Log("[CharId]" + moving.characterId); Debug.Log("[HouseName]" + moving.houseId); Debug.Log("[Moving]" + moving.moving); chrController remote = CharacterRoot.get().findCharacter(moving.characterId); // 이사 쿼리 발행. if (remote != null) { if (moving.moving) { Debug.Log("cmdQueryHouseMoveStart"); QueryHouseMoveStart query = remote.cmdQueryHouseMoveStart(moving.houseId, false); if (query != null) { query.set_done(true); query.set_success(true); } } else { Debug.Log("cmdQueryHouseMoveEnd"); QueryHouseMoveEnd query = remote.cmdQueryHouseMoveEnd(false); if (query != null) { query.set_done(true); query.set_success(true); } } } // 이사 정보 보존. GlobalParam.get().remote_moving = moving; }
public void OnReceiveSyncGamePacket(PacketId id, byte[] data) { Debug.Log("Receive GameSyncPacket[CharacterRoot]."); SyncGamePacket packet = new SyncGamePacket(data); SyncGameData sync = packet.GetPacket(); Debug.Log("[CharId]" + sync.moving.characterId); Debug.Log("[HouseName]" + sync.moving.houseId); Debug.Log("[Moving]" + sync.moving.moving); if (sync.moving.characterId.Length == 0) { // 이사하지 않았다. return; } // 이사 정보 보존. GlobalParam.get().remote_moving = sync.moving; }
// Use this for initialization void Start() { GameObject shotPlayer = GameObject.Find("basket").GetComponent <GameRoot>().players[globalId]; if (shotPlayer != null) { if (globalId == GlobalParam.get().global_account_id) { shotPower = shotPlayer.GetComponent <FireCtrl>().GetShotPower(); } Debug.Log("Global Id : " + globalId); Debug.Log("Shot Power:" + shotPower * speed); } // 발사 초기값 rb = GetComponent <Rigidbody2D> (); rb.AddForce(transform.right * speed * shotPower); // 총알 생성위치 = FirePos firePos = transform.position; }
// ================================================================ // // 로컬 플레이어 만들기. public void createLocalPlayer(int account_global_index) { if (this.players.Count == 0) { AccountData account_data = AccountManager.get().getAccountData(account_global_index); string avator_name = "Player_" + account_data.avator_id; chrBehaviorLocal local_player = CharacterRoot.getInstance().createPlayerAsLocal(avator_name).GetComponent <chrBehaviorLocal>(); local_player.control.local_index = 0; local_player.control.global_index = account_global_index; local_player.position_in_formation = this.getInFormationOffset(account_global_index); SHOT_TYPE shot_type = GlobalParam.get().shot_type[account_global_index]; local_player.changeBulletShooter(shot_type); this.players.Add(local_player); } }
// 쿼리-이사 시작해도 되는가?. public QueryHouseMoveStart queryHouseMoveStart(string house_name, bool local = true) { QueryHouseMoveStart query = null; do { chrBehaviorNPC_House house = CharacterRoot.getInstance().findCharacter <chrBehaviorNPC_House>(house_name); if (house == null) { break; } query = new QueryHouseMoveStart(house_name); this.queries.Add(query); } while(false); // 이사 시작 요청을 보냅니다. GameObject netObj = GameObject.Find("Network"); if (netObj && local) { // Network 클래스의 컴포넌트 획득합니다. Network network = netObj.GetComponent <Network>(); // 이사 시작 요청을 보냅니다. MovingData moving = new MovingData(); moving.characterId = GameRoot.getInstance().account_name_local; moving.houseId = house_name; moving.moving = true; MovingPacket packet = new MovingPacket(moving); network.SendReliable <MovingData>(packet); // 이사 정보 보존. GlobalParam.get().local_moving = moving; } return(query); }