코인
Coddy의 Unity 게임: 스카이 레인 코스 레슨. 20개 중 13번째.
코인은 앞을 가로막는 것이 없을 때 플레이어가 차선을 바꿀 이유를 제공합니다. 각 조각에는 장애물 뒤쪽, 조각을 따라 4, 7, 10, 13 지점과 y 1에 한 차선으로 동전이 네 개씩 배치됩니다.
동전은 자체 스크립트로 회전합니다.
void Update()
{
transform.Rotate(0f, 0f, spinSpeed * Time.deltaTime);
}동전 프리팹은 옆으로 누워 있으므로 자체 z축이 위를 향합니다. z축을 중심으로 회전하면 탁자 위의 동전처럼 빙글빙글 돕니다.
동전을 수집하는 일은 Runner의 역할이며, 같은 OnTriggerEnter에서 처리합니다. 동전을 획득하면 game.AddCoin()을 통해 동전 수를 1 늘리고 해당 동전을 제거합니다.
챌린지
쉬움Coin에public float spinSpeed = 180f;와 위에 나온 Update를 추가하세요.Road에coinPrefab을 추가하고,Fill의 끝에서 무작위 레인에 z가4f + i * 3f인 코인 4개를 배치하세요.GameManager에public TMP_Text coinText;,public int coins;,public void AddCoin()을 추가하세요(코인을 하나 더 추가한 다음ShowScore()를 호출). ShowScore에서도coinText.text = "Coins: " + coins;를 설정하세요.Runner.OnTriggerEnter에서else if (other.CompareTag("Coin"))인 경우 코인을 추가하고 코인을 제거하세요.
직접 해보기
using UnityEngine;
public class Runner : MonoBehaviour
{
public float laneWidth = 2.5f;
public float laneSpeed = 16f;
public float jumpHeight = 1.6f;
public float gravity = -40f;
public float slideTime = 0.7f;
public int lane;
private CharacterController controller;
private GameManager game;
private float fallSpeed;
private float slide;
void Start()
{
controller = GetComponent<CharacterController>();
game = FindFirstObjectByType<GameManager>();
}
void Update()
{
if (!game.over)
{
if (Input.GetKeyDown(KeyCode.A) || Input.GetKeyDown(KeyCode.LeftArrow)) lane = Mathf.Max(-1, lane - 1);
if (Input.GetKeyDown(KeyCode.D) || Input.GetKeyDown(KeyCode.RightArrow)) lane = Mathf.Min(1, lane + 1);
bool jump = Input.GetKeyDown(KeyCode.W) || Input.GetKeyDown(KeyCode.UpArrow) || Input.GetKeyDown(KeyCode.Space);
if (jump && controller.isGrounded)
{
fallSpeed = Mathf.Sqrt(jumpHeight * -2f * gravity);
StopSlide();
}
if ((Input.GetKeyDown(KeyCode.S) || Input.GetKeyDown(KeyCode.DownArrow)) && controller.isGrounded)
{
slide = slideTime;
Resize(0.5f);
}
}
if (slide > 0f)
{
slide -= Time.deltaTime;
if (slide <= 0f) StopSlide();
}
if (controller.isGrounded && fallSpeed < 0f) fallSpeed = -2f;
fallSpeed += gravity * Time.deltaTime;
float targetX = lane * laneWidth;
float x = Mathf.MoveTowards(transform.position.x, targetX, laneSpeed * Time.deltaTime);
Vector3 move = new Vector3(x - transform.position.x, fallSpeed * Time.deltaTime, 0f);
controller.Move(move);
}
void StopSlide()
{
if (transform.localScale.y < 1f) Resize(1f);
slide = 0f;
}
void Resize(float height)
{
controller.enabled = false;
transform.position += Vector3.up * (height - transform.localScale.y);
transform.localScale = new Vector3(1f, height, 1f);
controller.enabled = true;
}
void OnTriggerEnter(Collider other)
{
if (game.over) return;
if (other.CompareTag("Obstacle"))
{
game.GameOver();
}
}
}
Unity 게임: 스카이 레인의 모든 레슨
직접 연습해 보세요: Unity 플레이그라운드