728x90
1. 사운드 추가
GameManager -> Audio Source 컴포넌트 추가
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PlayerHealth : MonoBehaviour
{
public int startHealth; //시작 체력
public int currentHealth; //현재 체력
public bool isDie; //사망 상태
public Animator animator; //애니메이터
public Slider healthSlider; //체력 슬라이더
public Image damageImage; // 피격 데미지 이미지
private float flashTime = 5f; //피격 데미지 효과 표시 시간
private Color flashColor = new Color(1f, 0f, 0f, 1f); // 붉은색(r,g,b,a)
public AudioClip hitSound; //피격 사운드
public AudioClip deathSound; // 사망 사운드
public AudioSource audioSource; // 사운드 재생기
//컴포넌트 참조
public PlayerMovement movement;
public PlayerShot shot;
private bool damaged; // 피격상태
// Start is called before the first frame update
void Start()
{
currentHealth = startHealth; //시작 체력 설정
}
private void Update()
{
if (damaged)
{
//피격 칼라 효과 처리
damageImage.color = flashColor;
}
else
{
// 피격 칼라 효과 복원
damageImage.color = Color.Lerp(
damageImage.color, Color.clear, flashTime * Time.deltaTime);
}
damaged = false;
}
public void TakeDamage(int damage)
{
damaged = true; //피격 칼라 효고 처리 설정
audioSource.clip = hitSound;
audioSource.Play();
//체력 감소
currentHealth -= damage;
//체력이 1이고 이미 사망한 상태가 아니라면
if (currentHealth <= 0 && !isDie)
{
Death(); //사망 처리
}
//체력 게이지 처리
healthSlider.value = currentHealth;
}
//몬스터 사망 처리
public void Death()
{
//사망 상태 설정
isDie = true;
audioSource.clip = deathSound;
audioSource.Play();
//체력 슬라이더 비활성화
healthSlider.gameObject.SetActive(false);
//현재 체력 슬라이더의 부모 게임오브젝트의 Transform을 참조
//Transform.parent <- 부모 접근 속성
Transform healthUITransform = healthSlider.transform.parent;
//체력 표시용 UI 비활성화
healthUITransform.gameObject.SetActive(false);
//사망 애니메이션 재생
animator.SetTrigger("Die");
shot.DisableEffects(); //발포 이팩트 비활성화
movement.enabled = false; //이동 컴포넌트 비활성화
shot.enabled = false; //발포 컴포넌트 비활성화
}
}
2. 슈팅 사운드 추가
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerShot : MonoBehaviour
{
//발포 시간 관련 속성들
public float fireDelayTime; // 발포 주기
public float fireRange; //발포 길이
private float time; //발포 주기 계산 시간
// 발포 피격 관련 속성들
private Ray shootRay = new Ray(); // 레이생성
private RaycastHit shootHit; //레이 충돌 정보
private int shootableMask; // 발포 충돌 레이어 마스크(충돌 레이어 정수값)
public int damagePerShot; //피격 데미지
// 발포 효과 관련 속성들
public ParticleSystem gunParticleSys; //발포 이펙트 파티클 컴포넌트 참조
public LineRenderer fireLine; //발포 라인 효과 (라인랜더러)
public Light faceLight; // 발포 스팟 라이트 효과
public Light gunLight; // 발포 포인트 라이트 효과
public float effectDisplayTime; //발포 효과 재생 시간
public Transform firePos; //발포위치
public AudioClip shotSound; // 발포소리
public AudioSource audioSouce; //발포 소리 재생기
// Start is called before the first frame update
void Start()
{
// 충돌 레이어 이름으로 충돌 마스크 값을 구함
shootableMask = LayerMask.GetMask("Shootable");
}
// Update is called once per frame
void Update()
{
//시간을 계산함
time += Time.deltaTime;
//마우스 왼쪽 버튼을 누르고
if (Input.GetButton("Fire1") && time >= fireDelayTime)
{
Shot(); //발포 처리
}
if (time >= fireDelayTime * effectDisplayTime)
{
DisableEffects(); // 이펙트 비활성화
}
}
public void DisableEffects()
{
//조명 끄기
gunLight.enabled = false;
faceLight.enabled = false;
//라인 비활성화
fireLine.enabled = false;
}
void Shot()
{
//발포 소리 재생
audioSouce.clip = shotSound;
audioSouce.Play();
time = 0f;
//이펙트 라이트 on
gunLight.enabled = true;
faceLight.enabled = true;
//발포 파티클 재생
gunParticleSys.Stop();
gunParticleSys.Play();
//라인렌더러 활성화
fireLine.enabled = true;
//라인시작점 인덱스 : 0, 두번쨰 연결점 인덱스 : 1, ......2,3,4
//라인랜더러의 시작점을 총구 위치로 설정
fireLine.SetPosition(0, firePos.position);
//발포 레이 시작 위치 설정
shootRay.origin = firePos.position;
//발포 레이의 방향 설정
shootRay.direction = firePos.forward;
//
if (Physics.Raycast(shootRay, out shootHit, fireRange, shootableMask))
{
//레이가 충돌한 지점까지 라인의 끝점을 설정함
fireLine.SetPosition(1, shootHit.point);
//관통된 게임 오브젝트에 EnemyHealth 컴포넌트 존재하는지 확인함
EnemyHealth health = shootHit.collider.GetComponent<EnemyHealth>();
if (health != null)
{
health.TakeDamage(damagePerShot, shootHit.point);
}
}
else
{
//레이의 충돌이 없으면 레이 방향으로 지정된 발포 길이만큼으로 라인의 끝점을 설정함
fireLine.SetPosition(1, shootRay.origin + shootRay.direction * fireRange);
}
Debug.Log("발포!!!");
}
}
* 오류나는 코드 수정
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//AI(Navigation) 사용
using UnityEngine.AI;
//적군 이동 처리
public class EnemyMovement : MonoBehaviour
{
//공격 대상 (추적대상)
public Transform attackTarget;
//네브메쉬 에이전트 참조
public NavMeshAgent navMeshAgent;
//몬스터 애니메이터
public Animator animator;
public EnemyHealth enemyHealth;
private PlayerHealth playerHealth;
public Rigidbody rigidbody3d;
// Start is called before the first frame update
void Start()
{
//플레이어 게임오브젝트를 찾음 (태그로)
GameObject player = GameObject.FindGameObjectWithTag("Player");
// 츨레이어 체력 컴포넌트 참조
playerHealth = player.GetComponent<PlayerHealth>();
//플레이어를 추적대상으로 설정
attackTarget = player.transform;
}
// Update is called once per frame
void Update()
{
if (!navMeshAgent.enabled) return;
if (enemyHealth.currentHealth > 0 && playerHealth.currentHealth > 0)
{
//플레이어를 추적함
navMeshAgent.SetDestination(attackTarget.position);
}
else
{
rigidbody3d.isKinematic = true;
//추적 이동 중단
navMeshAgent.enabled = false;
}
}
}
3. 슬라임 사운드 추가
Prefabs -> Audio Source 추가
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class EnemyHealth : MonoBehaviour
{
//시작 체력
public int startHealth;
//현재체력
public int currentHealth;
//사망 상태
public bool isDie;
//애니메이터 컴포넌트 참조
public Animator animator;
public ParticleSystem hitParticle;
public ParticleSystem deathParticle;
public Renderer bodyRenderer;
public AudioClip hitSound; //피격 사운드
public AudioClip deathSound;
public AudioSource audioSource; // 사운드 재생기
// Start is called before the first frame update
void Start()
{
currentHealth = startHealth;
}
//피격 처리 (피격 데미지)
public void TakeDamage(int damage, Vector3 hitPos)
{
audioSource.clip = hitSound;
audioSource.Play();
currentHealth -= damage;
if (currentHealth <= 0 && !isDie)
{
Death(); //사망 처리
}
if (isDie) return;
hitParticle.transform.position = hitPos;
hitParticle.Play();
}
//몬스터 사망 처리
public void Death()
{
//점수 증가
GameManager.score++;
//사망 상태 설정
isDie = true;
audioSource.clip = deathSound;
audioSource.Play();
//사망 애니메이션 재상
animator.SetTrigger("Die");
//네비게이션 이동 중단
GetComponent<NavMeshAgent>().isStopped = true;
}
//사망 애니메이션 이벤트 메소드
public void OnDieAnimationEvent()
{
bodyRenderer.enabled = false;
deathParticle.Play();
Destroy(gameObject, deathParticle.main.duration);
}
}
4. 거북이 적군 추가
Slime 복제 -> unpack prefab -> 기존 거북이 Transform 복사, 붙여넣기
5. 애니메이터 복제(재사용)
Create -> New Animator Override Controller
적군생성기에 추가
적군 3:1 비율로 생성
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyGenerator : MonoBehaviour
{
public Transform[] genPositions; //생성 위치들
public GameObject[] enemyPrefabs; // 생성 몬스터 참조
public float genDelayTime; // 생성 주기
public PlayerHealth playerHealth;
// Start is called before the first frame update
void Start()
{
//몬스터 생성 타이머
InvokeRepeating("EnemyGenTimer", 2f, genDelayTime);
}
void EnemyGenTimer()
{
if (playerHealth.currentHealth <= 0) return;
int genIndex = Random.Range(0, genPositions.Length);
Vector3 genPosition = genPositions[genIndex].position;
float x = Random.Range(genPosition.x = 1f, genPosition.x + 1f);
float z = Random.Range(genPosition.x = 1f, genPosition.z + 1f);
genPosition = new Vector3(x, 0f, z);
int type = Random.Range(0, 3);
if (type == 0)
{
Instantiate(enemyPrefabs[1], genPositions[genIndex].position, genPositions[genIndex].rotation);
}
else
{
Instantiate(enemyPrefabs[0], genPositions[genIndex].position, genPositions[genIndex].rotation);
}
}
}
다른 코드로 변경해서 실행
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyGenerator : MonoBehaviour
{
public Transform[] genPositions; //생성 위치들
public GameObject[] enemyPrefabs; // 생성 몬스터 참조
public float genDelayTime; // 생성 주기
public PlayerHealth playerHealth;
public enum MONSTER_TYPE { SLIME, TURTLE };
// public MONSTER_TYPE monsterType = MONSTER_TYPE.SLIME;
// Start is called before the first frame update
void Start()
{
//몬스터 생성 타이머
InvokeRepeating("EnemyGenTimer", 2f, genDelayTime);
}
void EnemyGenTimer()
{
if (playerHealth.currentHealth <= 0) return;
int genIndex = Random.Range(0, genPositions.Length);
Vector3 genPosition = genPositions[genIndex].position;
float x = Random.Range(genPosition.x = 1f, genPosition.x + 1f);
float z = Random.Range(genPosition.x = 1f, genPosition.z + 1f);
genPosition = new Vector3(x, 0f, z);
int type = Random.Range(0, 3);
if (type == 0)
{
Instantiate(enemyPrefabs[(int)MONSTER_TYPE.TURTLE], genPosition, genPositions[genIndex].rotation);
}
else
{
Instantiate(enemyPrefabs[(int)MONSTER_TYPE.SLIME], genPosition, genPositions[genIndex].rotation);
}
}
}
EnemyGenerator -> Enemy Prefabs Size 2 -> 슬라임/거북이 연결
'Unity' 카테고리의 다른 글
[유니티] Photon 배우기 (0) | 2021.06.01 |
---|---|
[유니티] RPG 게임 만들기2 (0) | 2021.05.28 |
[유니티] 3D 슈팅게임 2 (0) | 2021.05.27 |
[유니티] 3D 슈팅게임 만들기 (0) | 2021.05.21 |
[유니티] 네이게이션 (0) | 2021.05.20 |
댓글