본문 바로가기

게임개발

UFO Controller 코드

using UnityEngine;
using UnityEngine.SceneManagement;

 

using UnityEngine.UI;
public class UFOController : MonoBehaviour
{
public GameObject cubePrefab; // 큐브 프리팹에 대한 참조
public Text myScore;
public float moveSpeed = 10f; // 이동 속도
public float maxLandingSpeed = 10f; // 최대 착륙 속도
public float rotationSpeed = 5f; // 회전 속도
public float verticalSpeed = 5f; // 수직 속도
public float maxSpeed = 20f; // 최대 속도
public float maxVerticalSpeed = 10f; // 최대 수직 속도
public float verticalAcceleration = 2f; // 수직 가속도
public float stationMoveDistance = 10f; // 스테이션이 이동할 수 있는 최대 거리
private AudioSource audioSource; // AudioSource 컴포넌트에 대한 참조
public AudioClip spaceBarSound; // 스페이스바 사운드 클립
public AudioClip defeatSound; // 패배 사운드 클립
public AudioClip scoreSound; // 점수 사운드 클립
public AudioClip backgroundMusic; // 배경 음악 오디오 클립 변수
private AudioSource backgroundMusicAudioSource; // 배경 음악용 AudioSource에 대한 참조
private bool spacePressed = false;
private Rigidbody rb;
private bool isRising = false;
private int score = 0; // 점수를 저장하는 변수
private Transform stationTransform; // 스테이션의 변환에 대한 참조
private GameObject spawnedCube; // 생성된 큐브에 대한 참조
private void Start()
{
myScore = GameObject.Find("Score").GetComponent<Text>();
rb = GetComponent<Rigidbody>();
rb.freezeRotation = true;

 

// 스테이션의 변환에 대한 참조 가져오기
stationTransform = GameObject.FindGameObjectWithTag("Station").transform;

 

// AudioSource 컴포넌트에 대한 참조 가져오기
audioSource = GetComponent<AudioSource>();
// 배경 음악용 AudioSource 가져오기 또는 생성하기
backgroundMusicAudioSource = gameObject.AddComponent<AudioSource>();
// 배경 음악 로드 및 재생
if (backgroundMusic != null)
{
backgroundMusicAudioSource.clip = backgroundMusic;
backgroundMusicAudioSource.loop = true; // 반복 재생 활성화
backgroundMusicAudioSource.Play();
}
// 스테이션을 초기 무작위 위치로 이동
if (stationTransform != null)
{
MoveStationToRandomPosition();
}
if (backgroundMusicAudioSource != null)
{
float desiredVolume = 0.6f; // 60% 볼륨
backgroundMusicAudioSource.volume = desiredVolume;
}
}
private void Update()
{
// UFO 이동
float horizontalInput = Input.GetAxis("Horizontal");
float verticalInput = Input.GetAxis("Vertical");
Vector3 inputDir = transform.forward * verticalInput + transform.right * horizontalInput;
inputDir.Normalize();
// 수평 이동을 위한 힘 적용

 

Vector3 targetVelocity = inputDir * moveSpeed;
// 수평 속도를 목표 속도로 부드럽게 조절
rb.velocity = Vector3.Lerp(rb.velocity, targetVelocity, Time.deltaTime * maxSpeed);
// UFO를 수평으로 회전
float mouseX = Input.GetAxis("Mouse X");
transform.Rotate(Vector3.up * mouseX * rotationSpeed);
if (Input.GetKeyDown(KeyCode.Space) && !isRising)
{
// 스페이스바를 누르면 상승 시작
isRising = true;

 

// spacePressed 플래그를 true로 설정
spacePressed = true;
// 스페이스바 사운드 재생
if (spaceBarSound != null)
{
audioSource.PlayOneShot(spaceBarSound);
}
}
if (Input.GetKeyUp(KeyCode.Space))
{
spacePressed = false;
audioSource.Stop();
}
if (isRising)
{
// 마우스 입력에 따라 UFO를 위아래로 이동
float mouseY = Input.GetAxis("Mouse Y");
Vector3 newPosition = transform.position + Vector3.up * mouseY * verticalSpeed * Time.deltaTime;
transform.position = newPosition;
// 수직 가속도 적용
float currentVerticalSpeed = rb.velocity.y;
float newVerticalSpeed = currentVerticalSpeed + verticalAcceleration * Time.deltaTime;
// 수직 속도 제한
newVerticalSpeed = Mathf.Clamp(newVerticalSpeed, -maxVerticalSpeed, maxVerticalSpeed);
// 새로운 수직 속도 적용
rb.velocity = new Vector3(rb.velocity.x, newVerticalSpeed, rb.velocity.z);
// 스페이스바를 놓거나 최대 수직 속도에 도달하면 상승 플래그 재설정
if (Input.GetKeyUp(KeyCode.Space) || Mathf.Abs(newVerticalSpeed) >= maxVerticalSpeed)
{
isRising = false;
}
}
// 큐브가 존재하는지 확인
if (spawnedCube != null)
{
// 큐브와 UFO 간의 거리 계산
float distance = Vector3.Distance(spawnedCube.transform.position, transform.position);
// 큐브를 삭제해야 할 최대 거리 정의
float maxDistance = 5.0f; // 필요에 따라 값 조정
//

 

 

 

 

 

 

 

 

 

 

  1. cubePrefab은 UFO가 착륙할 때 생성될 큐브 프리팹을 참조합니다.
  2. moveSpeed, rotationSpeed, verticalSpeed 등은 UFO의 이동 및 회전 속도를 나타냄
  3. audioSource와 backgroundMusicAudioSource는 UFO의 사운드와 배경 음악을 다루는 데 사용
  4. spacePressed는 스페이스바를 눌렀을 때의 상태를 나타냄
  5. rb는 UFO의 Rigidbody 컴포넌트를 참조
  6. stationTransform은 스테이션의 Transform을 나타냄
  7. spawnedCube는 UFO와 연관된 생성된 큐브를 참조
  8. Start() 함수에서는 필요한 초기화 및 설정 작업을 수행. 스테이션을 초기 위치로 이동시키고 배경 음악을 재생.
  9. Update() 함수에서는 주요한 게임 로직이 실행. 키보드 및 마우스 입력을 받아 UFO의 이동, 회전, 상승, 큐브 생성 등을 처리.
  10. OnCollisionEnter() 함수에서는 UFO가 벽, 운석 또는 스테이션과 충돌했을 때의 상황을 처리하며, 충돌에 따른 점수 변동과 스테이션 이동을 다룸.
  11. MoveStationToRandomPosition() 함수에서는 스테이션을 무작위 위치로 이동시키는 데 사용.
  12. SpawnCubeUnderUFO() 함수에서는 UFO 아래에 큐브를 생성.

 

 

 

 

GameObject.Find("Score").GetComponent<Text>();

>>씬에서 이름이 "Score"로 설정된 게임 오브젝트를 찾는 명령어.

이를 찾으면 해당 UI 요소의 Text 컴포넌트를 가져오기 위해 GetComponent<Text>()를 사용합니다.

즉, 이 코드는 씬 내에서 "Score"라는 이름을 가진 UI 텍스트 요소를 찾아서 그것을 myScore 변수에 연결하는 역할을 합니다. 이렇게 하면 이후 코드에서 myScore를 사용하여 UI 텍스트에 대한 작업을 할 수 있게 됩니다.

 

 

 

stationTransform = GameObject.FindGameObjectWithTag("Station").transform;

 

이 코드는 "Station"이라는 태그를 가진 게임 오브젝트를 찾아서 해당 게임 오브젝트의 Transform 컴포넌트를 가져오는 역할을 합니다.

GameObject.FindGameObjectWithTag("Station")는 씬 내에서 "Station"이라는 태그를 가진 게임 오브젝트를 찾습니다. 씬에서 게임 오브젝트를 태그로 식별하는 데 사용됩니다.

그리고 그것이 찾아지면, transform 속성을 사용하여 해당 게임 오브젝트의 Transform 컴포넌트를 가져와 stationTransform 변수에 할당합니다. 이렇게 함으로써 이후 코드에서 stationTransform을 사용하여 해당 게임 오브젝트의 Transform에 접근할 수 있게 됩니다.

 

 

 

 

 

// UFO 이동
float horizontalInput = Input.GetAxis("Horizontal");
float verticalInput = Input.GetAxis("Vertical");
Vector3 inputDir = transform.forward * verticalInput + transform.right * horizontalInput;
inputDir.Normalize();
// 수평 이동을 위한 힘 적용


Vector3 targetVelocity = inputDir * moveSpeed;
// 수평 속도를 목표 속도로 부드럽게 조절
rb.velocity = Vector3.Lerp(rb.velocity, targetVelocity, Time.deltaTime * maxSpeed);
// UFO를 수평으로 회전
float mouseX = Input.GetAxis("Mouse X");
transform.Rotate(Vector3.up * mouseX * rotationSpeed); 

 

 

 

UFO의 이동과 회전을 제어하는 부분입니다.

  1. Input.GetAxis("Horizontal") 및 Input.GetAxis("Vertical")은 사용자의 키보드나 조이스틱 입력에 따른 수평 및 수직 입력을 읽어옵니다.
  2. transform.forward는 UFO의 전방 벡터, transform.right는 UFO의 오른쪽 벡터를 나타냅니다. horizontalInput은 UFO가 좌우로 이동하는 데 사용되고, verticalInput은 전진/후진 이동에 사용됩니다.
  3. inputDir은 사용자 입력을 기반으로 만들어진 방향 벡터를 나타내며, Normalize() 함수를 통해 이 벡터를 정규화합니다(크기가 1인 방향 벡터로 만듭니다).
  4. targetVelocity는 UFO가 이동할 목표 속도를 나타냅니다. moveSpeed 변수에 의해 조절되며, 방금 계산한 방향 벡터 inputDir와 곱하여 설정됩니다.
  5. rb.velocity는 UFO의 현재 속도를 나타냅니다. Vector3.Lerp 함수를 사용하여 현재 속도에서 목표 속도로 부드럽게 변화하도록 합니다. Time.deltaTime * maxSpeed는 변화 속도를 결정하는 요소로, maxSpeed는 UFO의 최대 이동 속도를 나타냅니다.
  6. Input.GetAxis("Mouse X")는 마우스의 가로 이동에 대한 입력을 가져옵니다. 이 값에 rotationSpeed를 곱하여 UFO를 좌우로 회전시킵니다. transform.Rotate를 사용하여 UFO를 회전시킵니다.
  7. Vector3.Lerp는 선형보간법을 이용한 벡터이다. 부드럽게 이동하고싶을때 사용됨
  8. Mathf.Lerp -> 숫자간의 선형보간    Vector2.Lerp -> Vector2 간의 선형보간  Vector3.Lerp -> Vector3간의 선형보간

 

 

 

'게임개발' 카테고리의 다른 글

유니티 프로젝트 이름 변경법  (2) 2023.12.08
UFOcameraController  (2) 2023.12.07
유니티 Random.Range 를 알아보자.  (0) 2023.12.01
운석을 무작위로 이동시켜보자.  (0) 2023.12.01
PlayerPrefs  (0) 2023.10.11