VioletaBabel

63. Photon Tutorial (9) 본문

BCA/8. Photon
63. Photon Tutorial (9)
Beabletoet 2018. 8. 7. 17:35

UI Canvas가 있는 씬에서 Slider를 하나 추가한다.

이름은 Player UI로 하고, Middle-Center로 설정한 후 width는 80, height는 15로 설정한다.

자식 중 background의 컬러는 빨강으로 하고,  자식 중 Fill Area-Fill의 색은 녹색으로 둔다.

Player UI의 자식으로 Text를 하나 추가하고 이름은 player Name Text로 한다.

그 다음 Player UI를 프리팹으로 저장하고 하이에라키에서 지운다.


PlayerUI.cs를 만들어 다음과 같이 입력한다.

//PlayerUI.cs
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class PlayerUI : MonoBehaviour
{
public Text PlayerNameText;
public Slider PlayerHealthSlider;
public Vector3 ScreenOffset = new Vector3(0f, 30f, 0f);
private PlayerManager _target;
private float _characterControllerHeight = 0f;
private Transform _targetTransform;
private Vector3 _targetPosition;
private void Awake()
{
this.GetComponent<Transform>().SetParent(GameObject.Find("Canvas").GetComponent<Transform>());
}
private void Update()
{
if (PlayerHealthSlider != null)
PlayerHealthSlider.value = _target.Health;
if (_target == null)
{
Destroy(this.gameObject);
return;
}
}
private void LateUpdate()
{
if(_targetTransform!=null)
{
_targetPosition = _targetTransform.position;
_targetPosition.y += _characterControllerHeight;
this.transform.position = Camera.main.WorldToScreenPoint(_targetPosition) + ScreenOffset;
}
}
public void SetTarget(PlayerManager target)
{
if (target == null)
{
Debug.LogError("<Color=Red><a>Missing</a></Color> PlayerMakerManager target for PlayerUI.SetTarget.", this);
return;
}
_target = target;
_targetPosition = _target.transform.position;
_targetTransform = _target.transform;
CharacterController _characterController = _target.GetComponent<CharacterController>();
if (_characterController != null)
_characterControllerHeight = _characterController.height;
if (PlayerNameText != null)
PlayerNameText.text = _target.photonView.owner.NickName;
}
}


그리고 PlayerManager.cs를 다음과 같이 수정한다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
//PlayerManager.cs
using System.Collections;
using UnityEngine;
using UnityEngine.EventSystems;
public class PlayerManager : Photon.PunBehaviour, IPunObservable
{
    public GameObject Beams;
    public float Health = 1f;
    public static GameObject LocalPlayerInstance;
    public GameObject PlayerUiPrefab;
    private bool IsFiring;
 
    private void Awake()
    {
        if (Beams == null)
            Debug.LogError("<Color=Red><a>Missing</a><Color> Beams Reference."this);
        else
            Beams.SetActive(false);
        if (photonView.isMine)
            PlayerManager.LocalPlayerInstance = this.gameObject;
        DontDestroyOnLoad(this.gameObject);
    }
    private void Start()
    {
        CameraWork _cameraWork = this.gameObject.GetComponent<CameraWork>();
        if (_cameraWork != null)
        {
            if (photonView.isMine)//이것이 내꺼냐?
                _cameraWork.OnStartFollowing();//그럼 얘만 따라다니자
        }
        else
            Debug.LogError("<Color=Red><a>Missing</a></Color> CameraWork Component on playerPrefab."this);
 
        if (PlayerUiPrefab != null)
        {
            GameObject _uiGo = Instantiate(PlayerUiPrefab) as GameObject;
            _uiGo.SendMessage("SetTarget"this, SendMessageOptions.RequireReceiver);
        }
        else
            Debug.LogWarning("<Color=Red><a>Missing</a></Color> PlayerUiPrefab reference on player Prefab."this);
 
    }
    private void Update()
    {
        if (photonView.isMine) // 얘도 플레이어 자기 캐릭만 동작해야하니까 랩핑함.
            ProcessInputs();
        if (Health <= 0f)
            GameManager.instance.LeaveRoom(); // 체력이 0이 되면 게임 오버
        if (Beams != null && IsFiring != Beams.GetActive())
            Beams.SetActive(IsFiring);
    }
 
    void ProcessInputs()
    {
        if (Input.GetButtonDown("Fire1"))
            if (!IsFiring)
                IsFiring = true;
        if (Input.GetButtonUp("Fire1"))
            if (IsFiring)
                IsFiring = false;
    }
 
    private void OnTriggerEnter(Collider other)
    {
        if (!photonView.isMine)//자기 거인지 확인
            return;
        if (!other.CompareTag("Beam"))
            return;
        Health -= 0.1f;
    }
 
    private void OnTriggerStay(Collider other)
    {
        if (!photonView.isMine)
            return;
        if (!other.CompareTag("Beam"))
            return;
        Health -= 0.1f * Time.deltaTime;
    }
 
    void IPunObservable.OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info)
    {   //메소드 안에서 stream 변수를 전달하였다. 네트워크를 타고 전송되며 이 호출로 데이터를 읽고 쓴다.
        //photonView.isMine이 true일 때 write, 아닐 때 read된다.
        if (stream.isWriting)//write일 때
            stream.SendNext(IsFiring);//data Stream에 추가
        else//read일 때
            this.IsFiring = (bool)stream.ReceiveNext();
    }
 
    //void CalledOnLevelWasLoaded(int level)
    //{
    //    if(!Physics.Raycast(transform.position))
    //}
 
    private void OnLevelWasLoaded(int level)
    {
        //플레이어 아래로 raycast하여 아무 것도 접촉하고 있지 않다면 경기장 중심부로 위치를 재조정함.
        if (!Physics.Raycast(transform.position, -Vector3.up, 5f))
            transform.position = new Vector3(0f, 5f, 0f);
 
        GameObject _uiGo = Instantiate(PlayerUiPrefab) as GameObject;
        _uiGo.SendMessage("SetTarget"this, SendMessageOptions.RequireReceiver);
    }
}
 
cs


참고로 GameManager.cs의 OnLevelWasLoaded() 속 내용은 함수 채로 PlayerManager.cs로 옮긴다.

그리고 실행하면 자알 작동함.

다만 여기서 빠진 것은 빔을 쏘았을 떄의 충돌처리 등이 부재함.

튜토리얼은 여기까지만 나와있다.

'BCA > 8. Photon' 카테고리의 다른 글

62. Photon Tutorial (8)  (0) 2018.08.07
61. Photon Tutorial (7)  (0) 2018.08.06
60. Photon Tutorial (6)  (0) 2018.08.06
59. Photon Tutorial (5)  (0) 2018.08.06
58. Photon Tutorial (4)  (0) 2018.08.06
Comments