골드 메탈 님의 유튜브 콘텐츠 클론 코딩


필요한 기능
1) HP
2) 속도
3) Sprite
4) 피격 이벤트
5) 제거
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | using System.Collections; using System.Collections.Generic; using UnityEngine; public class Enemy : MonoBehaviour { public float speed; public int health; public Sprite[] sprites; SpriteRenderer spriteRenderer; Rigidbody2D rigid; void Awake() { spriteRenderer = GetComponent<SpriteRenderer>(); rigid = GetComponent<Rigidbody2D>(); rigid.velocity = Vector2.down * speed; } void OnHit(int dmg) { health -= dmg; spriteRenderer.sprite = sprites[1]; Invoke("ReturnSprite", 0.1f); if (health <= 0) { Destroy(gameObject); } } void ReturnSprite() { spriteRenderer.sprite = sprites[0]; } void OnTriggerEnter2D(Collider2D collision) { if(collision.gameObject.tag == "BorderBullet") { Destroy(gameObject); } else if(collision.gameObject.tag == "PlayerBullet") { Bullet bullet = collision.gameObject.GetComponent<Bullet>(); OnHit(bullet.dmg); Destroy(collision.gameObject); } } } | cs |
Line 7~9: public 변수로 속도, HP, Sprite를 선언하여 Unity에서 매핑하도록 한다.
Line 11, 16: SpriteRenderer를 선언하여 피격당했을 때 sprite가 변경되도록 할 수 있다.
Line 21~31: 피격 당했을 때 dmg만큼 health를 감소시키고 0이하가 되면 파괴한다. 피격 당하면 두 번째 sprite로 렌더링되었다가 Invoke함수에 의해 0.1초 지연된 뒤 다시 원래 sprite로 돌아온다.
Line 18: Spawn되면 바로 속도를 지정해준다. 속도는 아래로만 향한다.
Line 38~51: 적이 맵을 빠져나가 BorderBullet에 도달하면 파괴하여 메모리 낭비를 줄인다. 또는 player의 탄환에 맞으면 OnHit함수를 호출해 피격 이벤트를 수행한다. 피격되면 탄환이 같이 사라져야 하기 때문에 collision이 Playerbullet이면 collision.gameObject가 탄환이므로 이를 삭제한다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | using System.Collections; using System.Collections.Generic; using UnityEngine; public class GameManager : MonoBehaviour { public GameObject[] enemyObjs; public Transform[] spawnPoints; public float maxSpawnDelay; public float curSpawnDelay; void Update() { curSpawnDelay += Time.deltaTime; if(curSpawnDelay > maxSpawnDelay) { SpawnEnemy(); maxSpawnDelay = Random.Range(0.5f, 3f); curSpawnDelay = 0; } } void SpawnEnemy() { int ranEnemy = Random.Range(0, 3); int ranPoint = Random.Range(0, 5); Instantiate(enemyObjs[ranEnemy], spawnPoints[ranPoint].position, spawnPoints[ranPoint].rotation); } } | cs |




