Unity

Unity - Shooting Game

kakaroo 2022. 10. 23. 10:27
반응형

 

1. PlayerMove

목표: 컨트롤에 따라 이동한다.

 

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

public class PlayerMove : MonoBehaviour
{
    public float speed = 5f;

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

    // Update is called once per frame
    void Update()
    {
        float h = Input.GetAxis("Horizontal");
        float v = Input.GetAxis("Vertical");

        Vector3 dir = new Vector3(h, v, 0);
        //transform.Translate(dir * speed * Time.deltaTime);    //아래와 같다.
        transform.position += dir * speed * Time.deltaTime; // P = P0 + vt
        
    }
}

 

2. Bullet

목표: 위로 정해진 속도에 따라 이동한다.

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

public class Bullet : MonoBehaviour
{
    public float speed = 5f;

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

    // Update is called once per frame
    void Update()
    {
        //1. 방향
        Vector3 dir = Vector3.up;

        //2. 이동
        transform.position += dir * speed * Time.deltaTime;
        
    }
}

 

3. Bullet Prefab 생성

 

4. PlayerFire

목표 : 발사버튼을 누르면 총알이 Player 위치에서 위로 나간다.

 

생성할 bulletPrefab과 PlayerPosition을 지정해준다.

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

public class PlayerFire : MonoBehaviour
{
    public float speed = 5f;
    public GameObject bulletPrefab;
    public GameObject playerPosition;

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

    // Update is called once per frame
    void Update()
    {
        //1. 발사버튼을 누르면
        if(Input.GetButtonDown("Fire1"))
        {
            //2. 총알을 만든다
            GameObject bullet = Instantiate(bulletPrefab);

            //3. 총알이 움직이는 건 bullet.cs에서 설정했기 때문에 총알의 위치만 선정한다. 
            bullet.transform.position = playerPosition.transform.position;
        }
    }
}

 

5. 목표물(적 : Enemy)

목표: Player를 향하거나 그냥 아래로 내려온다. Player를 맞추거나 총알에 맞으면 사라진다.

 

충돌효과를 나타내기 위해 RigidBody 설정

Add Component > Physics > RigidBody

스크립트에서 아래로 이동할 것이므로 Gravity는 uncheck

 

충돌 처리는 아래 함수를 사용

    private void OnCollisionEnter(Collision other)
    {
        //충돌시작
    }
    private void OnCollisionStay(Collision other)
    {
        //충돌중
    }
    private void OnCollisionExit(Collision other)
    {
        //충돌끝
    }
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Enemy : MonoBehaviour
{
    public float speed = 5f;

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

    // Update is called once per frame
    void Update()
    {
        Vector3 dir = Vector3.down;
        transform.position += dir * speed * Time.deltaTime;        
    }

    private void OnCollisionEnter(Collision other)
    {
        //충돌시작
        Destroy(other.gameObject);
        Destroy(gameObject);
    }
    private void OnCollisionStay(Collision other)
    {
        //충돌중
    }
    private void OnCollisionExit(Collision other)
    {
        //충돌끝
    }
}

 

6. 목표물 prefab 만들기

 

7. 목표물 매니저 만들기

목표 : 랜덤한 시간마다 목표물을 위치에 생성한다

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

public class EnemyManager : MonoBehaviour
{
    float currentTime;
    
    public float minTime = 1;
    public float maxTime = 5;

    float createTime = 1;    //1초
    public GameObject enemyPrefab;

    // Start is called before the first frame update
    void Start()
    {        
        createTime = UnityEngine.Random.Range(minTime, maxTime);
    }

    // Update is called once per frame
    void Update()
    {
        currentTime += Time.deltaTime;

        if(currentTime > createTime)
        {
            GameObject enemy = Instantiate(enemyPrefab);
            enemy.transform.position = transform.position;
            currentTime = UnityEngine.Random.Range(minTime, maxTime);
        }        
    }
}

목표물 위치는 한 군데에서 시작하므로 여러 군데에서 나오기 위해 EnemyManager를 Ctrl+D 로 복사해서 X 위치값만 변경해준다.

-30 부터 10씩 증가

 

8. 목표물이 Player를 향해 가도록 수정

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

public class Enemy : MonoBehaviour
{
    public float speed = 5f;

    Vector3 dir;

    // Start is called before the first frame update
    void Start()
    {
        int randValue = UnityEngine.Random.Range(0,10);
        if(randValue <= 3)
        {
            GameObject target = GameObject.Find("Player");  //Target 찾기
            dir = target.transform.position - transform.position; //방향 구하기
            dir.Normalize();    //방향의 크기를 1로
        }
        else
        {
            dir = Vector3.down;
        }
    }

    // Update is called once per frame
    void Update()
    {
        transform.position += dir * speed * Time.deltaTime;        
    }

    private void OnCollisionEnter(Collision other)
    {
        //충돌시작
        Destroy(other.gameObject);
        Destroy(gameObject);
    }
    private void OnCollisionStay(Collision other)
    {
        //충돌중
    }
    private void OnCollisionExit(Collision other)
    {
        //충돌끝
    }
}

 

9. 영역 감지

영역을 벗어나면 스스로 destory 가 되어야 한다. 좌우아래 Zone을 설정한다.

 

 

IsTrigger 옵션 활성화 : 물체가 부딪혔을 때 트리거가 자동으로 충돌했다는 함수를 호출

RigidBody > IsKinematic : 충돌할 수 있는 물체지만 물리적인 행동을 하지않도록 하는 옵션

 

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

public class DestroyZone : MonoBehaviour
{
    private void OnTriggerEnter(Collider other)
    {
        Destroy(other.gameObject);
    }
}

좌우아래 Zone이 서로 겹쳐서 게임을 시작하면 없어짐

Layer를 설정하고, 아래 동일한 Layer 끼리는 Physics 가 동작하지 않도록 설정한다.

Player, Bullet, Enemy 도 Layer를 지정해주고 아래와 같이 설정

반응형

'Unity' 카테고리의 다른 글

유니티 #8 - delay (코루틴, invoke)  (0) 2022.06.06
유니티 #7 - Audio source  (0) 2022.06.05
유니티 #6 - Time.deltaTime  (0) 2022.06.04
유니티 #5 - 화면 회전 고정  (0) 2022.06.03
유니티 #4 - 게임 제작 순서  (0) 2022.06.01