- 플레이어가 총을 쏴서 몬스터를 이동 및 공격, 죽였을때 설정.
- 아래 코드는 몬스터를 공격하면 플레이어를 쫓아와서 공격하는 코드.
- 몬스터가 죽었을때 네비메쉬를 비활성화하고, 이 스크립트를 비활성화 하는 코드
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class EnemyTrace : MonoBehaviour
{
[SerializeField] Transform target_Player;
[SerializeField] float chaseRange = 10f;
EnemyHealth enemyHealth;
NavMeshAgent agent;
Animator animator;
float distanceToTarget = Mathf.Infinity;
bool isProvoked;
void Start()
{
agent = GetComponent<NavMeshAgent>();
animator = GetComponent<Animator>();
enemyHealth = GetComponent<EnemyHealth>();
}
void Update()
{
if (enemyHealth.IsDead())
{
enabled = false;
agent.enabled = false;
}
// 타겟과 나 사이의 거리 구하기
distanceToTarget = Vector3.Distance(target_Player.position, transform.position);
if(isProvoked)
{
EngageTarget();
}
else if(distanceToTarget < chaseRange)
{
isProvoked = true;
//agent.SetDestination(target_Player.position);
}
}
public void OnTakeDamage()
{
isProvoked = true;
}
private void EngageTarget()
{
// stoppingDistance(목표와 X거리 앞에서 멈춤)보다 멀리있으면 이동.
if(distanceToTarget >= agent.stoppingDistance)
{
//추적
ChaseTarget();
}
if (distanceToTarget <= agent.stoppingDistance)
{
// 공격
AttackTarget();
}
}
private void AttackTarget()
{
animator.SetBool("Attack", true);
}
private void ChaseTarget()
{
if (agent.enabled)
{
agent.SetDestination(target_Player.position);
}
animator.SetTrigger("move");
animator.SetBool("Attack", false);
}
/*
private void OnDrawGizmosSelected()
{
Gizmos.color = Color.yellow;
Gizmos.DrawWireSphere(transform.position, chaseRange);
}
*/
private void OnDrawGizmos()
{
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(transform.position, chaseRange);
}
}
- 적 몬스터가 공격 당했을때 HP 감소와 사망했을때 애니메이션 처리하는 코드
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyHealth : MonoBehaviour
{
[SerializeField] float hp = 100f;
public float Hp { get { return hp; } }
Animator animator;
bool isDead = false;
public bool IsDead()
{
return isDead;
}
private void Start()
{
animator = GetComponent<Animator>();
}
public void TakeDamage(float damage)
{
BroadcastMessage("OnTakeDamage");
hp -= damage;
if (hp <= 0)
{
Die();
}
}
private void Die()
{
if (isDead) return;
isDead = true;
animator.SetTrigger("die");
Destroy(gameObject, 5f);
}
}
유니티 마우스 클릭 위치로 캐릭터 이동하기, 카메라가 캐릭터 따라다니기 (1) | 2024.09.18 |
---|---|
유니티 마우스로 게임화면 클릭한 위치를 카메라로부터 선 그리기 (2) | 2024.09.18 |
유니티 아이템,총알 습득하기 (0) | 2024.09.16 |
유니티 List, 오류 및 해결 (1) | 2024.09.16 |
유니티 총 타입 별로 총알 구분하기 (0) | 2024.09.16 |