본문 바로가기

유니티 2D 기본(Platformer Game)

5. 몬스터 AI 구현하기

결과

스크립트 생성 및 몬스터에게 주기

 

스크립트(EnemyMove)

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

public class EnemyMove : MonoBehaviour
{
    Rigidbody2D rigid;
    Animator anim;
    SpriteRenderer sprite;
    public int nextMove; //몬스터의 다음 이동 방향 결정 변수

    void Awake()
    {
        rigid = GetComponent<Rigidbody2D>();
        anim = GetComponent<Animator>();
        sprite = GetComponent<SpriteRenderer>();
        Invoke("think", 3); //3초 뒤 think 함수 호출 예약
    }

    void FixedUpdate()
    {
        //Move
        rigid.velocity = new Vector2(nextMove, rigid.velocity.y); //nextMove 변수 값에 따라 왼쪽으로 가거나 오른쪽으로 이동

        //Platform Check
        Vector2 frontVec = new Vector2(rigid.position.x + nextMove * 0.3f, rigid.position.y); //ray위치 정하기 
        Debug.DrawRay(frontVec, Vector3.down, new Color(0, 1, 0)); //ray 그리기
        RaycastHit2D rayHit = Physics2D.Raycast(frontVec, Vector3.down, 1, LayerMask.GetMask("Platform")); //ray쏘기
        if (rayHit.collider == null) { //몬스터가 Platform에 모서리에 다다랐을때, 몬스터보다 조금 앞에 위치한 ray가 아무것도 반환받지 못함을 인식
            turn(); //반대방향으로 전환
        }
    }

    void think() {
        //Set Next Active
        nextMove = Random.Range(-1, 2); //랜덤함수로 다음 이동 방향 결정. 정수 -1, 0, 1중에 하나 반환(2번째 매개변수는 랜덤값에 포함안됨)

        //Sprite Animation
        anim.SetInteger("walkSpeed", nextMove); //애니메이션 변경

        //Flip Sprite
        sprite.flipX = nextMove == 1 ? true : false; //nextMove 가 1일 경우 몬스터는 우 이동, -1이면 좌 이동
        
        //Recursive
        float nextThinkTime = Random.Range(2f, 5f); 다음 think 함수 호출 예약 시간 결정
        Invoke("think", nextThinkTime); //재귀함수
    }

    void turn() {
        nextMove *= -1;
        sprite.flipX = !sprite.flipX;
        CancelInvoke();
        Invoke("think", 3);
    }
}

Idle 애니메이션 -> Walk 애니메이션 전환 시 Conditions

Walk 애니메이션 -> Idle 애니메이션 전환 시 Conditions