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


public class MonsterMove : MonoBehaviour
{

    Rigidbody2D rigid;
    Animator anim;
    SpriteRenderer spriteRenderer;

    public int nextMove;//다음 행동지표를 결정할 변수

    // Start is called before the first frame update
    private void Awake()
    {
        rigid = GetComponent<Rigidbody2D>();
        anim = GetComponent<Animator>();
        // nextMove = Random.Range(-1, 2); //챗
        spriteRenderer = GetComponent<SpriteRenderer>();
        Invoke("Think", 5); // 초기화 함수 안에 넣어서 실행될 때 마다(최초 1회) nextMove변수가 초기화 되도록함

    }


    // Update is called once per frame
    void FixedUpdate()
    {
        nextMove = Random.Range(2, 5);
        //Move
        rigid.velocity = new Vector2(nextMove, rigid.velocity.y); //nextMove 에 0:멈춤 -1:왼쪽 1:오른쪽 으로 이동


        //자신의 한 칸 앞 지형을 탐색해야하므로 position.x + nextMove(-1,1,0이므로 적절함)
        Vector2 frontVec = new Vector2(rigid.position.x + nextMove * 5f, rigid.position.y);

        //한칸 앞 부분아래 쪽으로 ray를 쏨
        Debug.DrawRay(frontVec, Vector3.down, new Color(0, 1, 0));

        // 레이캐스트의 시작 위치 (몬스터의 현재 위치)
        Vector2 startVec = new Vector2(transform.position.x, transform.position.y);

        // 레이를 양옆 방향으로 쏩니다. 오른쪽 방향(1)과 왼쪽 방향(-1) 두 번 쏩니다.
        RaycastHit2D hitRight = Physics2D.Raycast(startVec, Vector2.right, 1, LayerMask.GetMask("Wall"));
        RaycastHit2D hitLeft = Physics2D.Raycast(startVec, Vector2.left, 1, LayerMask.GetMask("Wall"));

        // 양옆에 벽이 있으면 Turn 함수 호출
        if (hitRight.collider != null || hitLeft.collider != null)
        {
            Turn();
        }

    }

    //재귀함수
    void Think()
    {
        //Set Next Active
        nextMove = Random.Range(0, 2) * 2 - 1; // -1 또는 1을 랜덤하게 설정

        anim.SetInteger("WalkSpeed", nextMove);

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

        MoveMonster();

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

    void Turn()
    {
        nextMove = -nextMove;
        spriteRenderer.flipX = nextMove == 1;
        float nextThinkTime = Random.Range(0.1f, 0.2f);
        Invoke("Think", nextThinkTime);

    }
    void MoveMonster()
    {
        float moveSpeed = 3.0f; // 이동 속도를 조절해보세요
        Vector2 newPosition = rigid.position + new Vector2(nextMove * moveSpeed * Time.fixedDeltaTime, 0);
        rigid.MovePosition(newPosition);
    }

    void FlipSprite(bool flip)
    {
        // 스프라이트 렌더러 컴포넌트 가져오기
        SpriteRenderer spriteRenderer = GetComponent<SpriteRenderer>();

        // 좌우 반전 적용
        spriteRenderer.flipX = flip;
    }
}
실질적인 오류는 안뜨는데 왜 오른쪽으로만 이동하는지 모르겠습니다..

- dc official App