유니티/Photon

Photon 2

SUGI_ 2022. 9. 10. 22:04

방에 다 들어갔으면 씬을 전환해서 플레이를 진행

GameScene

- GetAxis vs GetAxisRaw
GetAxis : 0에서 1로 빠르게 움직이기 때문에 미끄러지듯 멈춤
GetAxisRaw : 버튼 0과 1로 바뀌기 때문에 방향이 바로 바뀜

- 속도 : 방향 dir * speed / 속력 : 스칼라 speed

- Vector3.forward vs transform.forward 
Vector3.forward : Global 의 앞방향으로 움직임
transform.forward : Player의 앞방향으로 움직임

- Player가 땅에 부딪히면 yVelocity 0으로 설정하는 이유
 > Gravity의 값이 누적되기 때문에 아래로 떨어질때 순간이동처럼 보이게된다

1 PlayerMove

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

// 사용자의 입력에 따라 이동하고 싶다. // 캐릭터 컨트롤러
// 스페이스바 누르면 점프
// 중력, 점프 힘, yVeolocity
public class PlayerMove : MonoBehaviour
{
    // 이동속력
    public float speed = 10;

    CharacterController cc;

    // 중력
    float gravity = -9.81f;
    // 점프파워
    public float jumpPower = 5;
    // y방향 속력
    float yVelocity; 

    // Start is called before the first frame update
    void Start()
    {
        cc = GetComponent<CharacterController>();

        // 현재체력을 최대체력으로 셋팅
        currHp = maxHp;
    }

    // Update is called once per frame

    void Update()
    {
        // 사용자의 입력에 따라
        // Input.GetAxisRaw -> 정확하게 바로 적용
        float h = Input.GetAxisRaw("Horizontal");
        float v = Input.GetAxisRaw("Vertical");

        // 방향을 정하고
        // = Vector3 dir = new Vector3(h, 0, v);
        // 내 방향을 앞방향으로 하고 싶다면
        Vector3 dir = transform.forward * v + transform.right * h;
        dir.Normalize();

        // 만약에 바닥에 닿아있다면 yVelocity를 0으로 하자
        if(cc.isGrounded)
        {
            yVelocity = 0;
        }

        // 만약 점프키를 누른다면 
        if (Input.GetButtonDown("Jump"))
        {
            // yVelocity에 jumpPower를 셋팅
            yVelocity = jumpPower;
        }

        //yVelocity값을 중력으로 감소시킨다.
        yVelocity += gravity * Time.deltaTime;

        // dir.y에 yVelocity값을 셋팅
        dir.y = yVelocity;

        // 이동하고 싶다.
        cc.Move(dir * speed * Time.deltaTime);
    }

    // 현재 체력
    public int maxHp = 10;
    public int currHp;
    // 피격되었을 때 호출되는 함수
    public void OnDamaged()
    {
        //1. 현재 체력 1 줄여주고
        currHp--;
        print("현재체력" + currHp);
        //2. 만약에 현재 체력이 0보다 같거나 작아지면
        if(currHp <= 0)
        {
            //3. 나를 파괴한다.
            Destroy(gameObject);
        }
    }
}

2 PlayerRot

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

// 마우스의 움직임에 따라서 
// 좌우 회전은 플레이어를!
// 상하 회전은 CamPos를!
public class PlayerRot : MonoBehaviour
{
    // 회전 속력
    public float rotSpeed = 200;

    //CamPos의 Transform
    public Transform camPos;

    // 회전값 누적 변수
    float rotX;
    float rotY;

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        //1. 마우스의 움직임을 받는다
        float mx = Input.GetAxis("Mouse X");
        float my = Input.GetAxis("Mouse Y");
        //2. 마우스의 움직임 값으로 회전값을 누적시킨다.
        rotX += mx * rotSpeed * Time.deltaTime;
        rotY += my * rotSpeed * Time.deltaTime;

        //3. 플레이어의 회전 y값을 셋팅한다. //부모기준으로 회전을 계산
        transform.localEulerAngles = new Vector3(0, rotX, 0);
        //4. CamPos의 회전 x값을 셋팅한다
        camPos.localEulerAngles = new Vector3(-rotY, 0, 0);
    }
}

3 PlayerFire

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerFire : MonoBehaviour
{
    // 파편효과
    public GameObject bulletImpactFactory;

    // 총알공장
    public GameObject bulletFactory;
    // 총구위치
    public Transform firePos;

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        //1. 왼쪽 컨트롤키 누르면
        if(Input.GetKeyDown(KeyCode.LeftControl))
        {
            FireRay();
        }

        //1. 왼쪽 알트키를 누르면
        if(Input.GetKeyDown(KeyCode.LeftAlt))
        {
            //2. 총알공장 총알 만든다
            GameObject bullet = Instantiate(bulletFactory);
            //3. 총구에 위치 시킨다
            bullet.transform.position = firePos.position;
            //4. 총알의 앞방향을 총구방향으로 한다
            bullet.transform.forward = firePos.forward;
        }
    }

    void FireRay()
    {
        //2. 카메라 중심, 카메라 앞방향으로 나가는 Ray를 생성
        Ray ray = new Ray(Camera.main.transform.position, Camera.main.transform.forward);
        //3. 생성된 Ray를 발사해서 어딘가 부딪혔다면
        RaycastHit hit;

        if (Physics.Raycast(ray, out hit))
        {
            // 맞은 놈에게 PlayerMove 컴포넌트를 가져온다.
            PlayerMove pm = hit.transform.GetComponent<PlayerMove>();
            // 만약에 가져온 컴포넌트가 null이 아니라면
            if (pm != null)
            {
                // OnDamaged 실행
                pm.OnDamaged();
            }

            //4. bulletImpact 효과를 재생한다.
            GameObject bulletImpact = Instantiate(bulletImpactFactory);
            //5. 만든효과를 부딪힌 위치에 놓는다
            bulletImpact.transform.position = hit.point;
            //6. 만든효과의 앞방향을 normal방향으로 한다.
            bulletImpact.transform.forward = hit.normal;
            //7. 2초 뒤에 파괴한다.
            Destroy(bulletImpact, 2);
        }
    }
}

 

4 Bullet

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Bullet : MonoBehaviour
{
    // 속력
    public float speed = 10;

    //폭발효과 공장
    public GameObject exploFactory;

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        Vector3 dir = transform.forward;

        transform.position += dir * speed * Time.deltaTime;
    }

    private void OnTriggerEnter(Collider other)
    {
        // 폭발효과 만든다.
        GameObject explo = Instantiate(exploFactory);
        // 폭발효과를 내 위치로 놓는다.
        explo.transform.position = transform.position;
        // 2초뒤에 폭발효과 파괴
        Destroy(explo, 2);

        // 나자신을 파괴한다
        Destroy(gameObject);
    }
}
728x90