중급 프로그래머 가는 길 재미있게 가보자!
안녕하세요. 프로그래머 JD입니다.
오늘부터는 전 시간에 예고한 타워 속도 조정과 쿨타임 코드를 작성해 보겠습니다.
우선 타워 속도 조정부터 시작해 보겠습니다.
public float turnSpeed = 10f;
void Update()
{
if (target == null)
return;
Vector3 dir = target.position - transform.position;
Quaternion lookRotation = Quaternion.LookRotation(dir);
// Vector3 rotation = lookRotation.eulerAngles;
Vector3 rotation = Quaternion.Lerp(partToRotate.rotation,lookRotation,Time.deltaTime* turnSpeed).eulerAngles;
partToRotate.rotation = Quaternion.Euler(0f, rotation.y, 0f);
}
추가와 수정 1줄이면 끝입니다.
우선 멤버 변수인 turnSpeed를 추가하고
Vector3 rotation = lookRotation.eulerAngles;이었던 부분을
Quaternion.Lerp(partToRotate.rotation, lookRotation, Time.deltaTime*turnSpeed). eulerAngles;
으로 수정합니다.
public static Quaternion Lerp(Quaternion a, Quaternion b, float t);
Lerp함수 원형입니다.
public Vector3 eulerAngles;
eulerAngles는 회전의 오일러 각도를 반환하는 것인데 각도 값을 형 변환한다고 생각하면 될 것 같아요.
그것을 Lerp함수로 수정한 이유는 회전을 속도로 변경한 것입니다.
다시 Lerp함수의 원형을 보시면
a, b, t 가 있는데 a각도를 t만큼 b까지 각도를 변경하는 것입니다.
예를 들어 보겠습니다. 0º에서 30º 를 목표로 0.1만큼 변경해라 그러면 Lerp(30º ,0º ,0.1)입니다.
그러면 Lerp() 함수는 3º 를 return 할 것입니다.
그렇게 되면 회전 속도가 느려지게 됩니다.
이런 식으로 게임의 레벨을 조정할 수 있습니다.
타워 쿨타임 작업을 해보겠습니다.
[Header("Attributes")]
public float range = 15f;
public float fireRate = 2f;
private float fireCountdown = 0f;
[Header("Unity Setup Fields")]
public string enemyTag = "Enemy";
public Transform partToRotate;
public float turnSpeed = 10f;
public GameObject bulletPrefab;
public Transform firePoint;
void Update()
{
if (target == null)
return;
Vector3 dir = target.position - transform.position;
Quaternion lookRotation = Quaternion.LookRotation(dir);
Vector3 rotation = Quaternion.Lerp(partToRotate.rotation,lookRotation,Time.deltaTime* turnSpeed).eulerAngles;
partToRotate.rotation = Quaternion.Euler(0f, rotation.y, 0f);
//추가
if(fireCountdown<=0f)
{
Shoot();
fireCountdown = 1f / fireRate;
}
fireCountdown -= Time.deltaTime;
}
void Shoot()
{
GameObject bulletGO = Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
Bullet bullet = bulletGO.GetComponent<Bullet>();
if (bullet != null)
bullet.Seek(target);
}
일단 [Header("Attibutes")]가 보입니다. 이것은 public으로 멤버 변수를 선언하면 에디트 창에 text에디트 창이 뜨는데 이것을 정렬할 수 있게 도와줍니다.

Attributes으로 글자가 생기면서 멤버 변수인 Range, Fire Rate 함수가 정렬된 것을 확인할 수 있습니다.
FireRate는 쿨타임 시간입니다.
fireCountdown 은 쿨타임 감소율입니다. 그래서 private로 선언했습니다. 이것은 자동으로 돼야 하니까요.
GameObjet bulletPrefab은 object가 제거될 때 생성되는 object입니다. 왠지 object를 하나 또 생성해야 할 것 같은 기분이 드네요.
FirePoint는 object 가 생성되는 point입니다.
오늘은 여기까지 작업하겠습니다.
다음엔 조건문부터 분석해 보겠습니다.
끝까지 읽어주셔서 감사합니다. brackeys 감사합니다.
출처 - www.youtube.com/watch?v=oqidgRQAMB8&list=PLPV2KyIb3jR4u5jX8za5iU1cqnQPmbzG0&index=5
'프로그래밍 > 유니티' 카테고리의 다른 글
| 유니티 3D 게임만들기 타워 디펜스-타워생성(5) (0) | 2020.10.08 |
|---|---|
| 유니티 3D 게임만들기 타워 디펜스-타워 생성(4) (0) | 2020.10.02 |
| 유니티 3D 게임만들기 타워 디펜스-타워 생성(2) (0) | 2020.09.29 |
| 유니티 3D 게임만들기 타워 디펜스-타워 생성(1) (0) | 2020.09.26 |
| 유니티 3D 게임만들기 타워 디펜스-몬스터 생성(6) (0) | 2020.09.23 |