10 강 전체 코드

==[플레이어]=========================================================================

using UnityEngine;
using System.Collections;
using UnityEngine.UI; // ui 추가

// MonoBehaviour 클래스릉 상속한 CPlayer 클래스
public class CPlayer : MonoBehaviour
{

    // 플레이어의 속도
    public float _speed;

    // 폭발 연기 이펙트 프리펩
    public GameObject _smokePrefeb;

    // 체력
    public int _hp;
    public int _score;

    // UI 체력바
    public Image _hpBarImage;
    // UI 점수
    public Text _scoreText;


    //위치값을 가지는 객체 변수 생성
    Vector2 pos;
    // 오브젝트가 생성되고 렌더링되기 바로 전에 호출되는 이벤트 함수
    void Start() { }

    // 매 프레임마다 호출되는 이벤트 함수
    void Update()
    {

        // 수평키 입력값 추출
        // -1(왼쪽) ~0 (정지) ~1 (오른쪽)
        float h = Input.GetAxis("Horizontal");
        float v = Input.GetAxis("Vertical");

        //오브젝트 이동 메소드
        //transform.Translate(방향 * 속도 * Time.deltaTime)  이동에 대한 벡터 값.
        //Vector2 => 좌우.(z값이 없음)
        transform.Translate(Vector2.right * h * _speed * Time.deltaTime);
        transform.Translate(Vector2.up * v * _speed * Time.deltaTime);

        // 이동제한 메소드 호출
        CheckArea();
    }

    // 이동제한 메소드
    void CheckArea()
    {
        pos = transform.position;

        if (pos.x <= -2.8f) pos.x = -2.8f;
        if (pos.x >= 2.8f) pos.x = 2.8f;
        if (pos.y <= -4.5f) pos.y = -4.5f;
        if (pos.y >= 4.5f) pos.y = 4.5f;

        transform.position = pos;
    }

    // [충돌 체크]
    // Collider2D.OnTriggerEnter2D(충돌체 정보)
    // 박스2D 물리엔진으로 부터 충돌을 통지 받음.
    // Is Trigger가 체크된 오브젝트와의 충돌 이벤트 함수.
    void OnTriggerEnter2D(Collider2D col)
    {
        //Destroy(col.gameObject);
        //프리팹 오브젝트 사용으로 오브젝트 네임 뒤에 (Clone) 를 넣어준다.

        if (col.tag == "metero" || col.tag == "item")
        {
            Destroy(col.gameObject);

            // 운석이랑 충돌 할 경우 스모크 이펙트 발생
            if (col.tag == "metero")
            {
                // 게임오브젝트형 객체 Smoke를 만들고
                GameObject Smoke =
                    // Smoke에 Instantiate 로 프리팹 게임오브젝트를 생성 한 뒤
                    // 충돌체의 위치에서 스모크 이펙트 생성    
                Instantiate(_smokePrefeb, col.transform.position, Quaternion.identity)
                    // 생성된 게임오브젝트를 반환한다.
                as GameObject;

                //float aa = MetGen.
                // 스모크 이펙트 사이즈                       

                // 스모크를 플레이어의 자식으로 설정
                // Smoke.transform.parent = transform;
                // 반환된 게임오브젝트를 0.3f 초 뒤에 삭제한다.
                Destroy(Smoke, 0.9f);

                //체력이 0이면 패스
                if (_hp <= 0) return;

                // 체력 감소
                _hp -= 10;

                // 게임 종료
                if (_hp == 0)
                {
                    Debug.Log(_scoreText.text);
                    // Application.LoadLevel("씬이름");
                    Application.LoadLevel("game_end");
                }

                // 체력 게이지 업데이트
                _hpBarImage.fillAmount = _hp * 0.01F;
            }
            else if (col.tag == "item")
            {
                // 현재 점수 텍스트에서 현재 점수 구해서 
                // Parse = 텍스트를 정수형으로
                _score = int.Parse(_scoreText.text);
                // 10점 추가함
                _score += 10;
                // 현재 점수 텍스트를 업데이트
                _scoreText.text = _score.ToString();
            }
        }
        //col.name = 부딪힌 오브젝트 네임
    }
}

==[메테오젠]=========================================================================
using UnityEngine; using System.Collections; public class MetGen : MonoBehaviour { // 운석 프리팹 // 오브젝트를 복제하기 위해 파일로 만들어 놓은것 // 운석 프리팹을 연결함 // 가변 배열 - 인스펙터에서 배열의 사이즈 설정 public Object[] metero; // 최소 생성 지연 시간 public float MinTime; // 최대 생성 지연 시간 public float MaxTime; public void randNumber() { float randScale = Random.Range(-0.7f, 1.0f); } // Use this for initialization void Start() { // 운석 생성 타이머를 시작함. 코루틴 시작 StartCoroutine(CreateMeteroTimer()); } // 운석 생성 타이머 public IEnumerator CreateMeteroTimer() { while (true) { // 랜덤 int randNum = Random.Range(0, 3); Debug.Log(randNum); // 지연시간 랜덤 추출 float dealyTime = Random.Range(MinTime, MaxTime); // 지연 yield return new WaitForSeconds(dealyTime); // 운석 확률 70% 설정법 // 0~10 까지랜덤한 수를 뽑고 // 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 // 7 : 3 : 1 비율로 떨어짐 int cr = Random.Range(0, 10); int mettNum = 0; if (cr > 6 && cr < 9) { mettNum = 1; } else if (cr == 9) { mettNum = 2; } else { mettNum = 0; } //Debug.Log("운석생성"); //게임오브젝트 복제하여 생성 //프리팹 생성 //Instantiate(프리팹오브젝트, 생성 위치, 생성 각도) //Instantiate는 리턴값이 있다. // 아이템을 제외한 운석 사이즈 랜덤 조정 float randScale = Random.Range(-0.9f, 1.0f); GameObject obj = Instantiate(metero[mettNum], transform.position, Quaternion.identity) as GameObject; if (mettNum == 2) { obj.transform.localScale += new Vector3(0, 0, 0); } else { obj.transform.localScale += new Vector3(randScale, randScale, randScale); } } } // Update is called once per frame void Update() { } }
==[메테오무브]=========================================================================
using UnityEngine; using System.Collections; using UnityEngine.UI; // 운석 클래스 public class CmetroMove : MonoBehaviour { public float speed; public float minSpeed; public float maxSpeed; Vector2 pos; //점수 text public Text _scoreText; // Use this for initialization void Start () { // 프리팹이 게임 오브젝트로 로드하고 스코어 점수 텍스트를 참조함 _scoreText = GameObject.Find("ScoreText").GetComponent<Text>(); } // Update is called once per frame void Update () { //float rndNum = Random.Range(minSpeed, maxSpeed); transform.Translate(-Vector2.up * speed * Time.deltaTime); ChectArea(); // Debug.Log(rndNum); } // 바닥 영역을 넘어가면 게임오브젝트 삭제 void ChectArea() { pos = transform.position; if (pos.y <= -5.22f) { Destroy(gameObject); // 현재 점수 텍스트에서 현재 점수 구해서 // Parse = 텍스트를 정수형으로 int score = int.Parse(_scoreText.text); // 10점 추가함 score += 1; // 현재 점수 텍스트를 업데이트 _scoreText.text = score.ToString(); } } }

댓글

이 블로그의 인기 게시물

날짜 시간 시간차 시간 계산 하기

코루틴에서 CallBack 함수 적용하기

C++ 언어 퍼센트 구하는 방법 / 기본 언어 퍼센트 구하는 방법