파워업 잡기
Coddy의 Unity 게임: 벽돌 깨기 코스 레슨. 19개 중 15번째.
파워업은 캐치를 직접 감지합니다. 트리거 콜라이더가 패들의 콜라이더에 닿고 두 물체가 모두 키네마틱이면 OnTriggerEnter가 호출되기에 충분합니다. 공을 지나쳐 떨어지기도 하므로 먼저 태그를 확인합니다.
열거형으로 종류를 지정하고 각 프리팹에서 인스펙터를 통해 종류를 설정하므로 하나의 스크립트로 둘 다 처리할 수 있습니다.
public enum Kind { Wide, Multiball }
public Kind kind;
if (kind == Kind.Multiball) Debug.Log("Three balls");other.GetComponent<Paddle>()는 파워업이 닿은 오브젝트에 있는 Paddle 스크립트를 찾습니다. 지금은 Widen이 로그만 출력하지만, 다음 수업에서 패들을 늘립니다.
챌린지
어려움패들이 떨어지는 파워업을 받아내게 하세요.
PowerUp에public enum Kind { Wide, Multiball }과public Kind kind;를 추가하세요(각 프리팹에서 kind를 설정합니다).OnTriggerEnter(Collider other)를 추가하세요.other.CompareTag("Paddle")가 아니면 반환하고, Wide 파워업이면other.GetComponent<Paddle>().Widen();을 호출한 다음Destroy(gameObject);를 실행하세요.Paddle에 지금은Wide paddle을 로그로 출력하는public void Widen()을 추가하세요.
‘플레이’를 누르고 초록색 파워업을 받아내세요. 파워업이 사라지고 Console에 Wide paddle이 표시됩니다. 그런 다음 ‘확인’을 누르세요.
직접 해보기
using UnityEngine;
using UnityEngine.InputSystem;
public class Paddle : MonoBehaviour
{
public float speed = 14f;
public float wallX = 8f; // 양쪽 벽의 안쪽 면은 -wallX와 wallX에 있다
Rigidbody rb;
void Awake()
{
rb = GetComponent<Rigidbody>();
}
void FixedUpdate()
{
float input = 0f;
if (Keyboard.current.leftArrowKey.isPressed || Keyboard.current.aKey.isPressed) input -= 1f;
if (Keyboard.current.rightArrowKey.isPressed || Keyboard.current.dKey.isPressed) input += 1f;
Vector3 target = rb.position + Vector3.right * input * speed * Time.fixedDeltaTime;
float halfWidth = transform.localScale.x / 2f;
target.x = Mathf.Clamp(target.x, -wallX + halfWidth, wallX - halfWidth);
rb.MovePosition(target);
}
}
Unity 게임: 벽돌 깨기의 모든 레슨
직접 연습해 보세요: Unity 플레이그라운드