개발/Unity

유니티 간보기 - 골드메탈 2D 따라하기_몬스터기초 AI

huiyu 2022. 2. 4. 19:43

아래 유튜브를 따라하고 있습니다.

https://www.youtube.com/watch?v=7MYUOzgZTf8&list=PLO-mt5Iu5TeZGR_y6mHmTWyo0RyGgO0N_&index=6 

 

 - 몬스터 역시 Player와 동일하게 애니메이션 설정하기.


 - 일단 한방향으로 움직이게 스크립트 짜서 몬스터에 붙여주기.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnemyMove : MonoBehaviour
{
    Rigidbody2D rigid;

    private void Awake()
    {
        rigid = GetComponent<Rigidbody2D>();
    }

    void FixedUpdate()
    {
        rigid.velocity = new Vector2(-1, rigid.velocity.y);
    }
}

 

똑똑하게 만들기
 - 2~5초간 생각 바꿔서 방향 바꾸기
 - 낭떠러지를 만나면 돌기
 - 돌고, 걷는 동작에 맞춰 애니메이션 넣기

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnemyMove : MonoBehaviour
{
    Rigidbody2D rigid;
    Animator animator;
    SpriteRenderer renderer;
    public int nextMove;

    private void Awake()
    {
        rigid = GetComponent<Rigidbody2D>();
        animator = GetComponent<Animator>();
        renderer = GetComponent<SpriteRenderer>();
        Invoke("Think", 5);
    }

    void FixedUpdate()
    {
        //Move
        rigid.velocity = new Vector2(nextMove, rigid.velocity.y);

        //Platform Check
        Vector2 frontVec = new Vector2(rigid.position.x + nextMove*0.3f, rigid.position.y);
        Debug.DrawRay(frontVec, Vector3.down, new Color(0, 1, 0));
        RaycastHit2D rayHit = Physics2D.Raycast(frontVec, Vector3.down, 1, LayerMask.GetMask("Platforms"));
        if (rayHit.collider == null)
        {
            Debug.Log("경고! 이 앞 낭떠러지다");
            Turn();
        }

    }

    void Think()
    {
        //Set Next Active
        nextMove = Random.Range(-1, 2);

        //Sprite Animation
        animator.SetInteger("WalkSpeed", nextMove);

        //Flip Sprite
        if(nextMove != 0)
        {
            renderer.flipX = nextMove == 1;
        }

        //Set Next Active
        float nextThinkTime = Random.Range(2f, 5f);
        Invoke("Think", nextThinkTime);
    }

    void Turn()
    {
        nextMove *= -1;
        renderer.flipX = nextMove == 1;
        CancelInvoke();
        Invoke("Think", 5);
    }
}

 

ㅎ훗 귀여웧ㅎㅎ

 

728x90
반응형