[유니티]탑다운 슈팅 따라하기 #6 적 공격
- 게임 개발 - Unity3d
- 2020. 3. 30. 00:00
안녕하세요 유랑입니다.
실력 향상을 위해서 오늘은 유튜브를 따라 하면서 공부하겠습니다.
궁금하신 점 있으시다면 댓글로 남겨주세요^^
1. 탑다운 슈팅 따라하기
이번 강의는 Sebastian Lague님께서 만든 예제이며,
유튜브를 보시면 자세한 내용을 배우실 수 있습니다.
유튜브 사이트 => 유튜브
1-1) 적 공격 구현
이번 시간에는 적의 공격 구현을
만들어 보겠습니다.
시작하기 테스트를 위해 첫 번째 적 소환 수를 바꿔줄게요.
1-2) 스크립트 작성 - Enemy
Enemy 스크립트에 내용을 추가할 겁니다.
생각보다 양이 많으니 잘 따라와 주세요.
using System.Collections;
using UnityEngine;
using UnityEngine.AI;
[RequireComponent(typeof(NavMeshAgent))]
public class Enemy : LivingEntity
{
// 상태 (기본, 추격, 공격)
public enum State{Idle, Chasing, Attacking};
State currentState;
NavMeshAgent pathfinder;
Transform target;
Material skinMaterial;
Color originColor;
float attackDistanceThreshold = 0.5f; // 공격 사정거리
float timeBetweenAttacks = 1; // 공격 딜레이
float nextAttackTime; // 다음 공격이 가능한 시간
float myCollisionRadius; // 자신의 충돌 범위
float targetCollisionRadius; // 목표의 충돌 범위
protected override void Start()
{
base.Start();
pathfinder = GetComponent();
skinMaterial = GetComponent().material;
originColor = skinMaterial.color;
currentState = State.Chasing;
target = GameObject.FindGameObjectWithTag("Player").transform;
myCollisionRadius = GetComponent().radius;
targetCollisionRadius = target.GetComponent().radius;
StartCoroutine(UpdatePath());
}
void Update()
{
if (Time.time > nextAttackTime)
{
// (목표 위치 - 자신의 위치) 제곱을 한 수
float sqrDstToTarget = (target.position - transform.position).sqrMagnitude;
if (sqrDstToTarget < Mathf.Pow(attackDistanceThreshold + myCollisionRadius + targetCollisionRadius, 2))
{
nextAttackTime = Time.time + timeBetweenAttacks;
StartCoroutine(Attack());
}
}
}
// 적 공격
IEnumerator Attack()
{
currentState = State.Attacking;
pathfinder.enabled = false; // 네비게이션 추적 종료
Vector3 originalPosition = transform.position;
Vector3 dirToTarget = (target.position - transform.position).normalized;
Vector3 attackPosition = target.position - dirToTarget * (myCollisionRadius);
float attackSpeed = 3;
float percent = 0;
skinMaterial.color = Color.red;
while (percent <= 1)
{
percent += Time.deltaTime * attackSpeed;
float interpolation = (-Mathf.Pow(percent, 2) + percent) * 4;
transform.position = Vector3.Lerp(originalPosition, attackPosition, interpolation);
yield return null;
}
skinMaterial.color = originColor;
currentState = State.Chasing;
pathfinder.enabled = true; // 네비게이션 추적 시작
}
// 적 추적
IEnumerator UpdatePath()
{
float refreshRate = 0.25f;
while (target != null)
{
if (currentState == State.Chasing)
{
Vector3 dirToTarget = (target.position - transform.position).normalized;
Vector3 targetPosition = target.position - dirToTarget * (myCollisionRadius + targetCollisionRadius + attackDistanceThreshold/2);
if (!dead)
{
pathfinder.SetDestination(targetPosition);
}
}
yield return new WaitForSeconds(refreshRate);
}
}
}
첫 번째로 적의 상태를 만들어 줍니다.
enum을 통해 구현해주었습니다.
두 번째로는 목표 위치와 자신의 위치를 이용해
공격을 합니다.
이때 콜라이더 크기를 이용해 정확한 값을 알아냅니다.
세 번째로는 적의 공격을 구현합니다.
공격을 할 때 상태와 네비게이션 설정을 바꾸고,
수학적 계산을 이용해 부드럽게 만들어 줍니다.
공격 상태를 판별하기 위해 머티리얼 색깔도 바꿔주었답니다^^
네 번째로는 추적 상태일 때만 적을 추적하며,
콜라이더 크기 값을 이용해 정지하도록 구현하였습니다ㅎㅎ
푸슝푸슝 이제 게임 다워졌네요~~
2. 마무리
오늘 강의는 여기까지입니다.
탑다운 슈팅을 따라하면서 적 공격을 만들어 보았습니다.
감사합니다.
수업자료: 탑다운 슈팅 따라하기 #6 적 공격