반응형

Enemy 스크립트 작성합니다 

 

Enemy 스크립트를 작성

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

public class Enemy : MonoBehaviour
{
    public GameObject deathVFX;
    public GameObject hitVFX;
    public Transform parent;
    public int scorePerHit = 15;
    public int hitPoint = 4;

    ScoreBoard scoreBoard;

    private void Start()
    {
        scoreBoard = FindObjectOfType<ScoreBoard>();
    }

    
    private void OnParticleCollision(GameObject other)
    {
        ProcessHit();
        //hitPoint 0 이하일때 적을 파괴한다 
        if (hitPoint <1 )
        {
            KillEnemy();
        }
                   
    }

    //점수를 증가한다 
    private void ProcessHit()
    {
        GameObject vfx = Instantiate(hitVFX, transform.position, Quaternion.identity);
        vfx.transform.parent = parent;
        hitPoint--;
        scoreBoard.IncreaseScore(scorePerHit);
    }

    //외부 물체와 부딛칠때 이팩트생성한다.그리고 삭제 
    private void KillEnemy()
    {
        GameObject vfx = Instantiate(deathVFX, transform.position, Quaternion.identity);
        vfx.transform.parent = parent;
        Destroy(gameObject);
    }


}

 

 

 

 

큐브(Cube) 이름을 Enemy로 바꿉니다 

 

 

빈 오브젝트를 만들고 이름을 Spawn A Runtime으로 바꿉니다 

 

 

 

 

 

 

 

 

각각 Enemy 에 스크립트를 붙이고 아래그림과 같이 이팩트와 오브젝트를 붙입니다 

 

Package Manager 를 열고 TextMeshPro를 설치합니다 

UI -> Text - TextMeshPro 를 실행합니다 

 

ScoreBoard 스크립트 작성

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

public class ScoreBoard : MonoBehaviour
{

    int score;

    TMP_Text scoreText;


    private void Start()
    {
        scoreText = GetComponent<TMP_Text>();
        scoreText.text = "Start";
    }
    public void IncreaseScore(int amountToIncrease)
    {
        score += amountToIncrease;
        scoreText.text = score.ToString();
    }
}

Text 를 왼쪽 아랫단에 보이게 합니다 

 

 

 

Canvas를 선택하고  Screen Space - Overlay 선택  Canvas Scaler -> Ui Scale Mode -> Scale with Screen Size ,  Reference Resolution  X : 1920 Y: 1080으로 합니다 

 

Text 이름을 ScoreBoard 로 합니다 

 

 

ScoreBoard 스크립트를 붙힘니다 

게임을 실행 시켜서  장애물을 파괴했을 때 점수와 이팩트가 잘 터지는지 확인합니다

 

게임자료

3DTimeLime_F.vol1.egg
10.00MB
3DTimeLime_F.vol2.egg
10.00MB
3DTimeLime_F.vol3.egg
9.75MB

반응형
반응형

아래 있는 Effect 유니티 파일을 다운로드합니다 

Effect.unitypackage
0.04MB

 

 

 

임포트 합니다 

 

 

 PlayerRig 오브젝트 자식으로 있는  PlayerShip을 선택하고   Prefabs 폴더 안에 있는 Laser 프리팹을 드래그하여 자식으로 놓고 하나 더 복사하여 이름을 Laser_Right , Laser_Left로 합니다 

그리고 각각의 위치를 비행기 날개에서 발사 되는 위치에 적당히 올려놓습니다 

 

 

 

PlayerControls 스크립트 수정합니다 

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.Rendering.HighDefinition;

public class PlayerControl : MonoBehaviour
{   
    public float controlSpeed = 10f;
    public float xRange = 12f;
    public float yRange = 10f;
    [SerializeField] GameObject[] lasers;

    public float positionPithcFactor = -2f;
    public float controlPithcfactor = -10f;
    public float positionYawFactor = 2f;

    public float controlRollFactor = -20f;
    [SerializeField] InputAction fire;

    float xThrow;
    float yThrow;
    void Update()
    {
        ProcessTranslation();
        ProcessRotation();
        ProcessFiring();
    }

    void OnEnable()
    {
        fire.Enable();
    }

    private void OnDisable()
    {
        fire.Disable();
    }

    //상하좌우로 움직일때 로컬 로테이션을 준다 
    void ProcessRotation()
    {
        //y축 로컬 움직임 팩터
        float pitchDueToPosition = transform.localPosition.y * positionPithcFactor;
        float pitchdueToControlThrow = yThrow * controlPithcfactor;


        float pitch = pitchDueToPosition + pitchdueToControlThrow;
        //x축 로컬 움직임 팩터
        float yaw = transform.localPosition.x * positionYawFactor;
        float roll = xThrow * controlRollFactor;

        //로컬축으로 로테이션한다
        transform.localRotation = Quaternion.Euler(pitch, yaw, roll);
    }
    private void ProcessTranslation()
    {
        //좌우 입력
        xThrow = Input.GetAxis("Horizontal");
        //상하 입력
        yThrow = Input.GetAxis("Vertical");

        //시간에 따라 좌우 움직임을 준다 
        float xoffset = xThrow * Time.deltaTime * controlSpeed;
        float rawXPos = transform.localPosition.x + xoffset;

        //플레이어 좌우 이동 제한
        float clampedXPos = Mathf.Clamp(rawXPos, -xRange, xRange);

        //시간에 따라 상하 움직임을 준다 
        float yoffset = yThrow * Time.deltaTime * controlSpeed;
        float rawYpos = transform.localPosition.y + yoffset;

        //플레이어 상하 이동 제한
        float clampedYPos = Mathf.Clamp(rawYpos, -yRange, yRange);

        //키를 누르면 오브젝트를 상하좌우로 움직이게 한다 
        transform.localPosition = new Vector3(clampedXPos, clampedYPos, transform.localPosition.z);
    }

    

    void ProcessFiring()
    {
    //마우스 오른쪽 버튼을 누르면 미사일(ON)시켜 발사하고 그러지 않을땐 Off 한다
        if (Input.GetButton("Fire1"))
        {
            SetLasersActive(true);
        }
        else
        {
            SetLasersActive(false);
        }
    }
    

   
    //레이져 발사 이팩트를 껐다 켰다 한다
    void SetLasersActive(bool isActive)
    {
        foreach (GameObject laser in lasers)
        {
            var emissionModule = laser.GetComponent<ParticleSystem>().emission;
            emissionModule.enabled = isActive;
        }
    }
  
}

 

Laser_Right , Laser_Left  오브젝트를 드래그 하여 PlayerControls 스크립트 Lasers 위치에 드래그하여 올려놓습니다 

 

 

 

 

게임을 실행시켜서 비행기에 총알이 나가는지 확인합니다 

 

총알이 튕겨져 나갈땐  Lasers 프리팹을 열고 Particle System -> Collision을 열고 Min Kill Speed 값을 올려 봅니다 

 

PlayerShip를 선택하고 Physics -> Box Collider를 선택합니다  

 

 

 

PlayerShip 를 선택하고 Physics -> Rigidbody를 선택합니다  

 

 

Box Collider -> is Trigger 체크하고 Use gravity 체크해제 하고 is Kinematic 체크합니다 

 

 

Collision Handler 스크립트 작성

비행기가 외부 물체와 부딪칠때 게임이 재실행하는 스크립트를 작성합니다 

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


public class CollisionHandler : MonoBehaviour
{
    public float loadDelay = 1f;
    public ParticleSystem crashVFX;



    //외부 물체와 충돌하였을때 
    private void OnTriggerEnter(Collider other)
    {
        StartCrashSequence();
    }

    //crashVFX 이팩트를 실행, PlayerControl실행을 중지한다.그리고 1초후 다음 씬으로 이동한다 
    private void StartCrashSequence()
    {      
        crashVFX.Play();
        GetComponent<PlayerControl>().enabled = false;
        GetComponent<MeshRenderer>().enabled = false;
        GetComponent<BoxCollider>().enabled = false;

        Invoke("ReloadLevel", loadDelay);
    }

    void ReloadLevel()
    {
        int currentSceneIndex = SceneManager.GetActiveScene().buildIndex;
        SceneManager.LoadScene(currentSceneIndex);
    }
}

 

 

PlayerShip에 드래그하여 붙입니다 

 

 

PlayerRig 하위 밑으로 Player Explosion VFX 프리팹을 드래그하여 놓고 비행체 중앙에 놓습니다 

 

Collision Handler 스크립트 Crash VFX 공간에 드래그 하여 Player Explosion VFX를 놓습니다 

 

비행기가 비행하는 선로에 큐브를 생성하여 비행기가 부딪칠 수 있도록 합니다 

 

 

File -> Build Settings 들어가서 현재 씬을 드래그하여 Build Settings에 올립니다 

게임을 실행하여 장애물인 큐브에 부딪 칠때  이팩트가 터지고 게임이 재실행되는지 확인합니다 

 

 

반응형
반응형

유니티 2023.1.2.1에서 작업

유니티 에셋을 들어가서 Realistic Terrain Collection Lite  무료 에셋을 다운로드합니다 

window -> Package Manager 를 열고  임포트 합니다

 

임포트 한 파일에서 Terrain 5 파일 안에 자기가 맘에 드는 Terrain 파일 하나를 골라 Hierarchy 안으로 끄집어 올려놓습니다  

 

 

 

 

 

에셋 스토어에 다시 들어가서 Star Sparrow Modular Spaceship 에셋을 다운 받습니다 

 

Package Manager 에서 임포트 하여 다운로드합니다 

 

 

 

 

 

다운로드한 Star Sparrow 파일에서 Prefabs 폴더의 Examples에서 맘에 드는 비행기를 하나 골라서 Hierarchy 위에 끄집어 올려놓습니다 

 

올려놓은 비행기의 이름을 PlayerShip 으로 바꾸고 Assets폴더에 Prefabs 폴더를 하나 만들어서 드래그하여 프리팹으로 만듭니다 

 

 

 

 

 

 

 

오른쪽 마우스 버튼을 눌러서  Create Empty 오브젝트를 만든 다음 이름을 PlayerRig 로 바꾸고  Transform 값을 아래 그림과 같이 놓습니다  그리고 자식으로 PlayerRig와 Transform 값을 같은 값으로 하고 아래 그림과 같이 자식으로 놓습니다 

그리고 PlayerRig 자식으로 Main Camera 를 두고 Transform 값을 아래 그림과 같이 하여 카메라 보는 각도가 비행기 뒤쪽에서 바라보게 끔 합니다 

 

 

 

 

 

Create Empty 를 만들고 이름을 Master Timeline으로 합니다 

Master Timeline 선택하고 Window -> Sequencing -> Timeline 을 클릭하여 Timeline 창을 보이게 합니다 

 

Master Timeline 오브젝트를 선택하고  Timeline 창에 Create 버튼을 클릭하고 타임라인저장할 Assets 폴더에 새로운 폴더를 만듭니다 

 

Master Timeline 오브젝트를 선택하고 Timeline 창에서 +버튼을 누르고   Animation Track 를 선택합니다 

 Timeline 창에서 오른쪽의 자물쇠 모야을 잠금으로 합니다 

 

 

PlayerRig 오브젝트를 드래그 하여 Timeline 창의 Animation Track에 드래그합니다  

 

Timeline 창에서 아래와 같이 빨간 버튼을 누릅니다 

 

PlayerRig를 움직이면 Timeline 시간대에 점이 찍힘니다 PlayerRig를 자기가 움직이고 싶은 위치와 Timeline 시간대에 갔다 놓으면 됩니다  

 

Timeline의 아래와 같이 선 모양의 아이콘을 클릭하면 Animated Values 가 나오는데 찍혀있는 점들을 움직이면 위치와 회전을 바꿀 수 있습니다 

 

 

 

 

 

아래와 같이 PlayerRig 움직여 Timeline 시간대에 점이 찍히는 방향대로 움직인 결과 입니다 

 

 

Assets에 Scripts 폴더를 만들고 새로운 스크립트를 생성하여 이름을 PlayerControl을 만듭니다

 

 

 

 

 

스크립트를 작성합니다 

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//using UnityEngine.InputSystem;
//using UnityEngine.Rendering.HighDefinition;

public class PlayerControl : MonoBehaviour
{   
    public float controlSpeed = 10f;
    public float xRange = 12f;
    public float yRange = 10f;
   

    public float positionPithcFactor = -2f;
    public float controlPithcfactor = -10f;
    public float positionYawFactor = 2f;

    public float controlRollFactor = -20f;
   

    float xThrow;
    float yThrow;
    void Update()
    {
        ProcessTranslation();
        ProcessRotation();    
    }

    //상하좌우로 움직일때 로컬 로테이션을 준다 
    void ProcessRotation()
    {
        //y축 로컬 움직임 팩터
        float pitchDueToPosition = transform.localPosition.y * positionPithcFactor;
        float pitchdueToControlThrow = yThrow * controlPithcfactor;


        float pitch = pitchDueToPosition + pitchdueToControlThrow;
        //x축 로컬 움직임 팩터
        float yaw = transform.localPosition.x * positionYawFactor;
        float roll = xThrow * controlRollFactor;

        //로컬축으로 로테이션한다
        transform.localRotation = Quaternion.Euler(pitch, yaw, roll);
    }
    private void ProcessTranslation()
    {
        //좌우 입력
        xThrow = Input.GetAxis("Horizontal");
        //상하 입력
        yThrow = Input.GetAxis("Vertical");

        //시간에 따라 좌우 움직임을 준다 
        float xoffset = xThrow * Time.deltaTime * controlSpeed;
        float rawXPos = transform.localPosition.x + xoffset;

        //플레이어 좌우 이동 제한
        float clampedXPos = Mathf.Clamp(rawXPos, -xRange, xRange);

        //시간에 따라 상하 움직임을 준다 
        float yoffset = yThrow * Time.deltaTime * controlSpeed;
        float rawYpos = transform.localPosition.y + yoffset;

        //플레이어 상하 이동 제한
        float clampedYPos = Mathf.Clamp(rawYpos, -yRange, yRange);

        //키를 누르면 오브젝트를 상하좌우로 움직이게 한다 
        transform.localPosition = new Vector3(clampedXPos, clampedYPos, transform.localPosition.z);
    }
   
}

 

 

PlayerShip 오브젝트를 선택하고 PlayerControl 스크립트를 드래그 하여 붙입니다

그리고 아래그림과 같이 데이터 값을 넣습니다 

게임을 실행시켜서 AD(좌우) WS(상하) 키를 움직여서 비행기가 화면을 벋어나지 않고 잘 움직이는지 확인합니다  

 

 

 

반응형

+ Recent posts