본문 바로가기

코딩/UNITY

{unity 코드 설명} JUST SHOOT playercontroller

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

public class playercontrol : MonoBehaviour
{
    public float playerSpd = 8f;
    public float fireSpd = 1f;
    public Rigidbody2D rigi;
    public Transform firePos;
    public Transform firePos2;
    public GameObject die_par;
    public int nowbullet;
    public static playercontrol instance;
    public GameObject mime;
    float nowTime;
    float lazermodeTime;
    float nextFire;
    bool isfiremode;
    bool isreloadmode;
    public GameObject bulletpre;
    private Vector3 target;
    public bool isinfinity;
    public bool isdeadmode;
    // Start is called before the first frame update
    private void Awake()
    {
        instance = this;
    }
    void mouseMove()
    {
    Vector2 pos = (transform.position - Camera.main.ScreenToWorldPoint(Input.mousePosition));
    float Zangle = Mathf.Atan2(pos.y, pos.x) * Mathf.Rad2Deg;
    transform.rotation = Quaternion.Euler(0, 0, Zangle+90);
    }
    void Start()
    {
        isdeadmode = false;
        Cursor.visible = true;
        lazermodeTime = 3;
        nowbullet = 25;
        nextFire = Time.time;
        rigi = GetComponent<Rigidbody2D>();
        isinfinity = false;
    }
    void after3second()
    {
        GameManager.instance.EndGame();
    }
    void Die()
    {
        gameObject.SetActive(false);
        Instantiate(die_par, transform.position, transform.rotation);
        Invoke("after3second", 3);
    }
    // Update is called once per frame
    private void OnParticleCollision(GameObject other)
    {
        if(other.tag == "enemy"||other.tag == "ger_enemy")
        {  
         Die();
        }
    }   
    private void OnTriggerEnter2D(Collider2D collision)
    {
        if(collision.tag == "enemy"||collision.tag == "rocket")
        {
            Die();
        }
        
    }
    private void OnCollisionEnter2D(Collision2D collision)
    {
        if(collision.transform.tag == "enemy")
        {
            Die();
        }
    }
    void Update()
    {
        float time = 0;
        
        float xInput = Input.GetAxis("Horizontal");
        float yInput = Input.GetAxis("Vertical");

        float xSpd = playerSpd * xInput;
        float ySpd = playerSpd * yInput;

        Vector3 velo = new Vector2(xSpd, ySpd);
        rigi.velocity = velo;
        mouseMove();
        Cursor.visible = true;
        if(time >=5)
        {
            time = 0;
            isinfinity = false;
            Debug.Log("end");
        }
        if (Input.GetMouseButton(0)&& nextFire<Time.time&&nowbullet != 0)
        {
            if (this.tag == "mine_player")
            {
                nextFire = Time.time + fireSpd;
                Instantiate(mime, firePos.position, transform.rotation);
                nowbullet--;
            }
            else
            {
                nextFire = Time.time + fireSpd;
                Instantiate(bulletpre, firePos.position, transform.rotation);
                //bullet = Instantiate(bulletpre, firePos2.position, transform.rotation);
                nowbullet--;
            }
        }
        if(Input.GetMouseButton(0)&&isinfinity == true)
        {
            
            Instantiate(bulletpre, firePos.position, transform.rotation);
        }
        if(isinfinity)
        {
            Debug.Log("eat");
            if(lazermodeTime>0)
            {
                lazermodeTime -= Time.deltaTime;
            }
            if(lazermodeTime<=0)
            {
                lazermodeTime = 3;
                GameManager.instance.islazermode = false;
            }
            
        }

        }
        
    }

네 삼겹살입니다. 약속한 대로 오늘은 코드 설명을 하겠습니다. 

상당히 스파게티 코드인점 이해 부탁드립니다.

모든 코드입니다. 137자 밖에 되지 않습니다.

시작시 싱글턴 디자인 패턴을 활용하기 위해 public static playercontroller instance; 변수를 선언 해 주고, 어웨이크 함수에서 자신을 할당해 줍니다.

마우스를 보는 방향으로 플레이어가 회전하게 하는 소스입니다. 각 UPDATE마다 실행되며, 카메라에서 마우스 위치를 받아 와서 바라보게 만듭니다. 끝에 Quaternion.Euler(0,0,Zangle+90);에서 +90은 만약 마우스 방향의 반대를 보고 있다면 해주시면 됩니다.

시작 부분 입니다. 기본적인 변수에 값을 할당해 줍니다.

후술하도록 하겠습니다.

죽으면 호출되는 함수입니다. 자신의 게임 오브젝트를 비 활성화하고 죽음 파티클을 생성후 3초 후 위 함수를 호출합니다.

모두 충돌을 감지하고 죽는 스크립트입니다.

움직이는 스크립트입니다. Input.Getaxis함수를 사용하여 어느 키가 눌렸는지 위치값을 받고, 플레이어 속도를 곱해서 rigidbodt2D.velocity에 할당해 줘서 움직임을 줍니다. 위에 설명한 함수인 MOUSEMOVE를 호출합니다.

이 if문은 마우스 우클릭을 하고, 연사시간이 지났을때, 현제의 총알의 개수가 0이 아니라면 실행됩니다.

자신의 tag를 검사해서 자신의 태그가 지뢰 캐릭터라면 지뢰를 생성하고, 아니라면 총알을 하나빼고 총알을 생성합니다.

무한 총알 모드일때 연사속도를 무한으로 하는 코드입니다.

무한 총알 모드상태일때 5초가 지나면 무한총알모드를 false로 바꿉니다.

총알 무한 상태의 시간을 설정하는 코드입니다. 

 

 

 

자 이렇게 플레이어 컨트롤러 스크립트 설명이 끝났습니다. 다음번엔... Gamemanager가 될것 같습니다.

 

게임은 https://drive.google.com/file/d/1bd9wpYu8KHxIwColYpplEUctVNMnEP21/view?usp=sharing 이걸 압축 풀어주시면 됩니다.