결과
스크립트 생성 및 몬스터에게 주기
스크립트(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
'유니티 2D 기본(Platformer Game)' 카테고리의 다른 글
7. 몬스터 밟아서 잡기 (0) | 2021.12.03 |
---|---|
6. 플레이어 피격 이벤트 구현 (0) | 2021.11.30 |
4. TileMap으로 플랫폼 만들기 (0) | 2021.11.26 |
4. 플레이어 점프 구현 & Raycast (0) | 2021.11.26 |
3. 2D에서 플레이어 이동 구현 (0) | 2021.11.25 |