본문 바로가기
PROGRAMING📚/Unity📑

[UNITY]Photon Pun2 (3) - 캐릭터 설정 해주기

별찌루 2024. 3. 18.
728x90
반응형

 

플레이어 캐릭터 스크립트(PlayerCtrl)를 만들어서 캐릭터가 움직이도록 만들어준다

 

using System.Collections;
using UnityEngine;

public class PlayerCtrl : MonoBehaviour
{
    [Header("Player Animaion")]
    public Animator playerAnimation;
    [Space]
    private float speed=10f;
    private float jumpForce = 5f;

     [Space]
    private Rigidbody characterRgb;

    private void Start()
    {
        characterRgb = GetComponent<Rigidbody>();
    }
    private void Update() {
        if(Input.GetKeyDown(KeyCode.Space)){
            Debug.Log("space input");
            characterRgb.AddForce(Vector3.up *jumpForce, ForceMode.Impulse);
        }
    }
    private void FixedUpdate()
    {   
        float inputX = Input.GetAxis("Horizontal");
        float inputZ = Input.GetAxis("Vertical");
        transform.position += new Vector3(inputX,0,0)*speed *Time.deltaTime;
    }
}

 

네트워크를 이용한 플레이어 동기화

 

플레이어 컨트롤을 만들어주고

여러개의 캐릭터를 띄워주기 위해서 다음과 같이 설정을 해주었다

 

 

캐릭터 안에 메인 카메라를 넣어주고

 

플레이어 안에 Photon View, Photon Rigidbody View , Photon Transform View 컴포넌트를 넣어준다

 

그리고 Enable teleport for large distances(원거리 순간이동 가능) 는 활성화 해주고

Synchronize Velocity(속도 동기화) 는 비활성화 해주었다

 

Photon과 동기화 하려는 모든 개체 들은 Resources 라는 특수 폴더 안에 있어야 하기 때문에

새로운 Resources 폴더를 생성 해주었다

 

 

만들어둔 Player 캐릭터를 폴더안에 끌어 넣어 프리팹화 시켜준다

그리고 하이어라키 안에 있던 캐릭터는 삭제해준다

 

다시 RoomManager 스크립트를 열어서

public GameObject player;

public Transform spawnPoint;

 

게임이 시작되면 생성할 플레이어 오브젝트와 캐릭터를 생성할 위치 값을 넣기 위해

두 개의 변수를 생성해 준다

 

빈 오브젝트를 생성하고 다음과 같이 SpawnPoint 이름을 지정하고 캐릭터가 생성될 위치를 지정해주었다

그리고 프리팹화 시켜준 플레이어와 스폰 포인트를 RoomManager 안에 넣어 준다

그리고 방에 연결 되었을 때 캐릭터를 생성해준다

 

public override void OnJoinedRoom()
    {
        base.OnJoinedRoom();
        Debug.Log("방과 연결됨");
        GameObject _player = PhotonNetwork.Instantiate(player.name, spawnPoint.position, Quaternion.identity);
    }

 

방에 들어오면 PhotonNetwork.Instantiate를 사용해서 플레이어를 생성해준다

그리고 시작 버튼을 누르면

 

플레이어가 생성된 것을 확인 할 수 있다

728x90
반응형

댓글