1、BirthPoint是所有出生点的父物体
2、BirthPointDefault是我们选取的默认出生点
大概思路是:
1、我们在每个人人物被实例化之前,先实例化出所有出生点(带有Collider并勾选Trigger的物体)。
2、判断默认出生点是否有人,有人的话对应出生点的bool IsthereAnyOne 为true。如果默认出生点的IsthereAnyOne为true,那么我们就在其他出生点遍历一遍,随机找到一个IsthereAnyOne为false的点出生。
3、假如所有出生点都站了人,那么就在默认出生点周边随机出生。
注意:实例化玩家之前必须先实例化出生点。这里我用了一个协程让玩家延迟0.5s出生,这0.5s可以做一个出场动画替代。否则会导致一个问题,多个玩家在同一个出生点出来造成重叠和碰撞
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
using Cinemachine;
using Photon.Realtime;
using UnityEngine.UI;public class GameManager : MonoBehaviourPunCallbacks
{Transform _BirthPoint; //所有出生点的父物体Transform _BirthPointDefault; //默认出生点public Text _playerNum; //玩家人数显示TextVector3 _birthPoint; //出生点GameObject temp;bool isChange = false;private void Awake(){temp = PhotonNetwork.Instantiate("BirthPoint", Vector3.zero, Quaternion.identity, 0);//实例化出生点_BirthPoint = temp.transform;_BirthPointDefault = temp.transform.GetChild(1);isChange = false; //}private void Start(){ReadyToPlay();}private void Update(){_playerNum.text = "当前有 " + PhotonNetwork.CurrentRoom.PlayerCount + " 名玩家在线";}//准备开始public void ReadyToPlay() {base.OnJoinedRoom();//实例化角色//GameObject Player = PhotonNetwork.Instantiate("Player", new Vector3(1, 1, 0), Quaternion.identity, 0);print("实例化角色");StartCoroutine(GetBirthPoint());}//获取合适的出生点 //先判断有几个可用的出生点,并存到List表中//判断默认出生地点是否可用,如果不可用则在其他可用的出生点随机生成public IEnumerator GetBirthPoint(){yield return new WaitForSeconds(0.5f);//这个List表用来存放所有没人站着、可作为出生点的IDList AnyOneID = new List();//如果默认出生点允许 则在此出现if (!_BirthPointDefault.GetComponent().IsthereAnyone) {_birthPoint = _BirthPointDefault.position;print("去默认出生点");}//如果默认出生点站了人,则随机从其他点出生else{for (int i = 0; i < _BirthPoint.childCount; i++){if (!_BirthPoint.GetChild(i).GetComponent().IsthereAnyone){//序列为i的点是可以作为出生点的AnyOneID.Add(i);}else {print(_BirthPoint.GetChild(i).name + "点有人站着");}}//当所有出生点都站了人,那么直接从默认出生点的上方出来if (AnyOneID.Count == 0){//从默认出生点周边随机生成_birthPoint = new Vector3(_BirthPointDefault.position.x + Random.Range(1, 2), _BirthPointDefault.position.y , _BirthPointDefault.position.z + Random.Range(1, 2));}else {//从AnyOneID表中随机找一个出生点int randomNum = Random.Range(0, AnyOneID.Count);_birthPoint = _BirthPoint.GetChild(AnyOneID[randomNum]).position;print("出生点是" + _BirthPoint.GetChild(randomNum) + "位置是 :" + _birthPoint);}}GameObject Player = PhotonNetwork.Instantiate("Player", new Vector3(_birthPoint.x, _birthPoint.y+1f, _birthPoint.z) , Quaternion.identity, 0);//_PlayerFollowCamera.Follow = Player.transform.GetChild(0);}//获取某个点的序号public int GetDefaultID(Transform point) {int id = 0;for (int i = 0; i < _BirthPoint.childCount; i++){if (_BirthPoint.GetChild(i).name == point.name) {id = i;break;}}return id;}
}