[패스트캠퍼스 수강 후기] 올인원 패키지 : 유니티 포트폴리오 완성 100% 환급 챌린지 48회차 미션 시작합니다.

04. 배틀로얄 - 41, 42 번을 진행합니다.




Shoot Behaviour 테스트를 위한 Unity 세팅을 진행해 줍니다.

 


Interactive Weapon 관련 세팅도 진행해 줍니다.




그리고 Unity를 플레이하면 무기 집고 조준 및 총 쏘기, 장전 등 잘 동작하는 것을 확인할 수 있습니다.




자 이제 생명력 처리를 하는 과정의 시작입니다.




Player/PlayerHealth 스크립트를 생성하고 코딩을 시작합니다.

/// 플레이어의 생명력을 담당
/// 피격시 피격 이팩트를 표시하거나 UI 업데이트를 함.
/// 죽었을 경우 모든 동작 스크립트 동작을 멈춤.
public class PlayerHealth : HealthBase
{
    public float health = 100f;
    public float criticalHealth = 30f;
    public Transform healthHUD;
    public SoundList deathSound;
    public SoundList hitSound;
    public GameObject hurtPrefab;
    public float decayFactor = 0.8f;
    
    private float totalHealth;
    private RectTransform healthBar, placeHolderBar;
    private Text healthLabel;
    private float originalBarScale;
    private bool critical;
    
    private void Awake() {
        myAnimator = GetComponent<Animator>();
        totalHealth = health;
        
        healthBar = healthHUD.Find("HealthBar/Bar").GetComponent<RectTransform>();
        placeHolderBar = healthHUD.Find("HealthBar/Placeholder").GetComponent<RectTransform>();
        healthLabel = healthHUD.Find("HealthBar/Label").GetComponent<Text>();
        originalBarScale = healthBar.sizeDelta.x;
        healthLabel.text = "" + (int)health;
    }
    
    private void Update() {
        if (placeHolderBar.sizeDelta.x > healthBar.sizeDelta.x) {
            placeHolderBar.sizeDelta = Vector2.Lerp(placeHolderBar.sizeDelta, healthBar.sizeDelta, 2f * Time.deltaTime);
        }
    }
    
    public bool IsFullLife() {
        return Mathf.Abs(health - totalHealth) < float.Epsilon;
    }
    
    private void UpdateHealthBar() {
        healthLabel.text = "" + (int)health;
        float scaleFactor = health / totalHealth;
        healthBar.sizeDelta = new Vector2(scaleFactor * originalBarScale, healthBar.sizeDelta.y);
    }
    
    private void Kill() {
        IsDead = true;
        gameObject.layer = TagAndLayer.GetLayerByName(TagAndLayer.LayerName.Default);
        gameObject.tag = TagAndLayer.TagName.Untagged;
        healthHUD.gameObject.SetActive(false);
        healthHUD.parent.Find("WeaponHUD").gameObject.SetActive(false);
        myAnimator.SetBool(AnimatorKey.Aim, false);
        myAnimator.SetBool(AnimatorKey.Cover, false);
        myAnimator.SetFloat(AnimatorKey.Speed, 0);
        foreach (GenericBehaviour behaviour in GetComponentsInChildren<GenericBehaviour>()) {
            behaviour.enabled = false;
        }
        SoundManager.Instance.PlayOneShotEffect((int)deathSound, transform.position, 5f);
    }
    
    public override void TakeDamage(Vector3 location, Vector3 direction, float damage, Collider bodyPart = null, GameObject origin = null) {
        health -= damage;
        UpdateHealthBar();
        if (health <= 0) Kill();
        else if (health <= criticalHealth && !critical) critical = true;
        SoundManager.Instance.PlayOneShotEffect((int)hitSound, location, 1f);
    }
}



PlayerHealth Script를 Attach하고 관련 설정을 하여 줍니다.



그리고 Unity 플레이를 진행해 보면 좌하단에 HealthBar 100 이 표시되는 것을 확인할 수 있습니다.



 

 

 

 



이제 플레이어 발소리 컴포넌트 제작을 시작합니다.




PlayerFootStep 스크립트를 생성하고 코딩을 시작합니다.

/// <summary>
/// 발자국 소리를 출력.
/// </summary>
public class PlayerFootStep : MonoBehaviour
{
    public SoundList[] stepSounds;
    private Animator myAnimator;
    private int index;
    private Transform leftFoot, rightFoot;
    private float dist;
    private int groundedBool, coverBool, aimBool, crouchFloat;
    private bool grounded;
    
    public enum Foot { LEFT, RIGHT, }
    private Foot step = Foot.LEFT;
    private float oldDist, maxDist = 0;
    
    private void Awake() {
        myAnimator = GetComponent<Animator>();
        leftFoot = myAnimator.GetBonTransform(HumanBodyBones.LeftFoot);
        rightFoot = myAnimator.GetBonTransform(HumanBodyBones.RightFoot);
        groundedBool = Animator.StringToHash(AnimatorKey.Grounded);
        coverBool = Animator.StringToHash(AnimatorKey.Cover);
        aimBool = Animator.StringToHash(AnimatorKey.Aim);
        crouchFloat = Animator.StringToHash(AnimatorKey.Crouch);
    }
    
    private void PlayFootStep() {
        if (oldDist < maxDist) return;
        oldDist = maxDist = 0;
        int oldIndex = index;
        while (oldIndex == index) {
            index = Random.Range(0, stepSounds.Length - 1);
        }
        SoundManager.Instance.PlayOneShotEffect((int)stepSounds[index], transform.position, 0.2f);
    }
    
    private void Update() {
        if (!grounded && myAnimator.GetBool(groundedBool)) PlayFootStep();
        grounded = myAnimator.GetBool(groundedBool);
        float factor = 0.15;
        if (grounded && myAnimator.velocity.magnitude > 1.6f) { // 움직이고 있다면..
            oldDist = maxDist;
            switch( step) {
                case Foot.LEFT:
                    dist = leftFoot.position.y - transform.position.y;
                    maxDist = dist > maxDist ? dist : maxDist;
                    if (dist <= factor) {
                        PlayFootStep();
                        step = Foot.RIGHT;
                    }
                    break;
                case Foot.RIGHT:
                    dist = rightFoot.position.y - transform.position.y;
                    maxDist = dist > maxDist ? dist : maxDist;
                    if (dist <= factor) {
                        PlayFootStep();
                        step = Foot.LEFT;
                    }
                    break;
            }
        }
    }
}

 



PlayFootStep 스크립트를 Attach하고 StepSound를 설정해 줍니다.




Unity 플레이를 하여 재생하여 캐릭터를 움직여 보면 걸을 때마다 소리가 재생되는 것을 확인할 수 있습니다.




<위의 코드들은 제가 보면서 주요한 함수, 코드를 확인하기 위해 타이핑한 용도로, 전체 소스코드가 아님에 주의해 주세요. 전체 코드는 교육 수강을 하면 완벽하게 받으실 수가 있답니다 ^^>

패스트캠퍼스 - 올인원 패키지 : 유니티 포트폴리오 완성 bit.ly/2R561g0

 

유니티 게임 포트폴리오 완성 올인원 패키지 Online. | 패스트캠퍼스

게임 콘텐츠 프로그래머로 취업하고 싶다면, 포트폴리오 완성은 필수! '디아블로'와 '배틀그라운드' 게임을 따라 만들어 보며, 프로그래머 면접에 나오는 핵심 개념까지 모두 잡아 보세요!

www.fastcampus.co.kr

 

+ Recent posts