VioletaBabel

59. Photon Tutorial (5) 본문

BCA/8. Photon
59. Photon Tutorial (5)
Beabletoet 2018. 8. 6. 15:00

새로운 씬 Kyle Test를 만든 후 Photon Unity Networking/Demos/Shared Assets 폴더의 Robot Kyle.fbx를 Hierarchy에 불러오자.

그리고 My Robot Kyle로 이름을 바꾼 후 리소스 폴더에 프리팹으로 만들어준다.


My Kyle Robot에 Character Controller 컴포넌트를 넣는다. 그리고 해당 컴포넌트의 Center.y 값을 1로 바꿔주자.

다음으로 Animator의 Controller 부분에 Kyle Robot을 넣어준 후 Speed 파라미터를 양수 값으로 바꾸자. 그러면 실행 시 애가 뛰어간다.



씬에 큐브를 넣어 포지션을 (0,-0.5,0)으로, 스케일을 (30,1,30)으로 하고 카메라를 적절히 배치하자.

그리고 안전빵으로 My Robot Kyle의 포지션 y값을 0.1만큼 올린다.


그리고 PlayerAnimatorManager.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
//PlayerAnimatorManager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class PlayerAnimatorManager : MonoBehaviour
{
    public float DirectionDampTime = 0.25f;
    private Animator animator;
    // Use this for initialization
    void Start()
    {
        animator = GetComponent<Animator>();
        if (!animator)
            Debug.LogError("PlayerAnimatorManager is Missing Animator Component"this);
    }
 
    // Update is called once per frame
    void Update()
    {
        if (!animator)
            return;
        AnimatorStateInfo stateInfo = animator.GetCurrentAnimatorStateInfo(0); // 현재 수행중인 animator의 state를 가져옴.
        if (stateInfo.IsName("Base Layer.Run"))
            if (Input.GetButtonDown("Fire2"))
                animator.SetTrigger("Jump");
        float h = Input.GetAxis("Horizontal");
        float v = Input.GetAxis("Vertical");
        if (v < 0)
            v = 0;
        animator.SetFloat("Speed", h * h + v * v);
        animator.SetFloat("Direction", h, DirectionDampTime, Time.deltaTime);
    }
}
 
cs

그럼 이제 wasd로 움직이기 시작하며, 알트를 누르면 점프한다.




플레이어 캐릭터의 왼쪽 눈 앞에 큐브를 추가하고 길쭉하게 만든 후 붉은 마테리얼을 넣는다.

그리고 눈에서 나가는 빔처럼 보이게 크기를 적당히 맞춰준다.

그 다음 이름을 Beam Left로 하고, 이를 복사해 오른쪽에도 Beam Right를 넣는다.

그리고 Beam Left와 Beam Right를 Beam의 자식으로 둔다. (Beam은 플레이어의 자식으로 두어 플레이어의 이동에도 그대로 반응하게 한다.)

Beam Right의 Collider를 삭제하고, Beam Left의 Collider 사이즈를 알아서 적당히 잘 조절한다.


그 뒤 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
using System.Collections;
using UnityEngine;
using UnityEngine.EventSystems;
 
public class PlayerManager : MonoBehaviour
{
    public GameObject Beams;
    bool IsFiring;
    private void Awake()
    {
        if (Beams == null)
            Debug.LogError("<Color=Red><a>Missing</a><Color> Beams Reference."this);
        else
            Beams.SetActive(false);
    }
    private void Update()
    {
        ProcessInputs();
        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;
    }
}
 
cs

로 해주고 이를 플레이어 캐릭터에 드래그 해 넣어준다.

그리고 Beams 프로퍼티에 아까 만든 빔을 드래그해 넣는다.

이제 왼쪽 컨트롤 키를 눌렀을 때 눈에서 빔이 나온다.




이제 공격 무기를 갖췄으니 체력을 넣는다.

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
//PlayerManager.cs
using System.Collections;
using UnityEngine;
using UnityEngine.EventSystems;
public class PlayerManager : Photon.MonoBehaviour
{
    public GameObject Beams;
    public float Health = 1f;
    bool IsFiring;
    private void Awake()
    {
        if (Beams == null)
            Debug.LogError("<Color=Red><a>Missing</a><Color> Beams Reference."this);
        else
            Beams.SetActive(false);
    }
    private void Update()
    {
        ProcessInputs();
        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;
    }
}
 
cs



체력을 넣었지만 게임 오버는 없으므로, 체력이 양수가 아니게 되면 게임 오버가 되도록 한다.

우선 GameManager.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
//GameManager.cs
using System.Collections;
using System;
using UnityEngine;
using UnityEngine.SceneManagement;
 
public class GameManager : Photon.PunBehaviour {
 
    static public GameManager instance;
 
    private void Start()
    {
        instance = this;
    }
 
    private void LoadArena()
    {
        if (!PhotonNetwork.isMasterClient) // 마스터 클라이언트인지 확인.
            Debug.LogError("PhotonNetwork : Trying to Load a level but we are not the master Client");
        Debug.Log("PhotonNetwork : Loading Level : " + PhotonNetwork.room.PlayerCount);
        PhotonNetwork.LoadLevel("Room for " + PhotonNetwork.room.PlayerCount);  //네트워크 메세지 큐를 잠시 멈추기 위해
                                                //레벨 로딩을 Wrap함.
                                                //이 메소드는 PhotonNetwork.isMessageQueueRunning을 false함.
                                                //그리고 레벨 로딩이 끝나면 enable.
                                                //룸 내의 로드된 레벨과 동기화를 위하여 
                                                //PhotonNetwork.automaticallySyncScene을 사용하도록 하였기에
                                                //룸 안의 모든 클라이언트의 레벨 로드를 유니티가 아닌 Photon이 하도록 함.
                                                //마스터인 경우에만 호출되어야 함.
    }
    public void OnLeftRoom()
    {
        SceneManager.LoadScene(0); // Photon Callback인 OnLeftRoom을 listen하여 0번 Scene인 Launcher를 로드한다.
    }
    public void LeaveRoom()
    {
        PhotonNetwork.LeaveRoom();  // 현재 참여하고 있는 룸을 떠나 마스터 서버로 되돌아간다.
                                    // autoCleanUp을 false로 하지 않았을 경우, PhotonView의 모든 네트워크 게임 오브젝트를 제거.
                                    // 마스터 서버도 되돌아가며, 오프라인 모드에서는 OnLeftRoom이 곧바로 호출됨.
                                    // 추상화를 위해 public 메소드로 wrap 함.
    }
 
    public override void OnPhotonPlayerConnected(PhotonPlayer other)
    {   //원격 플레이어가 룸에 들어왔을 때 호출. PhotonPlayer가 playerlist에 이미 추가된 시점에 불림.
        //특정 수의 플레이어로 게임이 시작 시, 이 콜백 내에서 Room.playerCount를 체크해 게임 시작이 가능한지 확인하기도 함.
        Debug.Log("OnPhotonPlayerConnected() " + other.NickName);
        if(PhotonNetwork.isMasterClient)
        {
            Debug.Log("OnPhotonPlayerConnected isMasterClient" + PhotonNetwork.isMasterClient);
            LoadArena();
        }
    }
 
    public override void OnPhotonPlayerDisconnected(PhotonPlayer other)
    {   //원격 플레이어가 룸을 나갔을 때 호출. PhotonPlayer가 playerlist에서 이미 제거된 시점에 불림.
        //클라이언트가 PhotonNetwork.leaveRoom을 호출할 때 이 메소드를 호출함.
        //원격 클라이언트의 연결이 끊어져도 이 콜백이 몇 초간의 타임아웃 후 실행 됨.
        Debug.Log("OnPhotonPlayerDisconnected() " + other.NickName);
        if(PhotonNetwork.isMasterClient)
        {
            Debug.Log("OnPhotonPlayerConnected is MasterClient " + PhotonNetwork.isMasterClient);
            LoadArena();
        }
    }
}
cs


이렇게 수정하고


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
//PlayerManager.cs
using System.Collections;
using UnityEngine;
using UnityEngine.EventSystems;
public class PlayerManager : Photon.MonoBehaviour
{
    public GameObject Beams;
    public float Health = 1f;
    bool IsFiring;
    private void Awake()
    {
        if (Beams == null)
            Debug.LogError("<Color=Red><a>Missing</a><Color> Beams Reference."this);
        else
            Beams.SetActive(false);
    }
    private void Update()
    {
        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;
    }
}
 
cs


이렇게 고쳐주면 된다.

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

61. Photon Tutorial (7)  (0) 2018.08.06
60. Photon Tutorial (6)  (0) 2018.08.06
58. Photon Tutorial (4)  (0) 2018.08.06
57. Photon Tutorial (3)  (0) 2018.08.06
56. Photon Tutorial (2)  (0) 2018.08.06
Comments