using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Forever_Chase : MonoBehaviour
{
// 유령이 플레이어을 계속 쫓아다닌다.
// 목표오브젝트(타겟-boy)
Rigidbody2D rb;
GameObject targetObject; // 타겟오브젝트를 찾기위한 변수선언
public float speed = 5; // 유령의 이동속도
public string targetObjectName; // 목표오브젝트에 이름 저장
public string showObjectName; // 표시할오브젝트 이름 저장(햄버거)
GameObject showObject; // 표시할 오브젝트를 찾아서 저장할 변수 선언
void Start()
{
// 리지드바디 컴포넌트 가져오기
rb = GetComponent<Rigidbody2D>();
// 중력을 0, 충돌후에 회전금지
rb.gravityScale = 0;
rb.constraints = RigidbodyConstraints2D.FreezeRotation;
// 타겟오브젝트 찾기
targetObject = GameObject.Find(targetObjectName); // 오브젝트의 이름으로 찾는방법
Time.timeScale = 1; // 처음부터 시간이 움직이게 처리한다.
// 유니티 실행시키자마자 햄버거를 지운다. 지우기전에 햄버거를 기억해둔다.
showObject = GameObject.Find(showObjectName); // 햄버거오브젝트 찾아서 저장
showObject.SetActive(false); // 플레이시키자마자 햄버거 안보이게(비활성화)
}
// 일정한 속도로 유령이 쫓아가게하기 위해서
void FixedUpdate()
{
// 유령이 목표오브젝트의 위치와 방향을 찾는다(벡터-속도: 크기+방향)
// 지역변수 dir
Vector2 dir = (targetObject.transform.position - this.transform.position).normalized;
// 벡터 : 배열객체, 2차원배열(x, y)
// 유령이 그 방향으로 계속 따라간다
float vx = dir.x * speed;
float vy = dir.y * speed;
rb.velocity = new Vector2(vx, vy);
// 이동방향에서 좌우반전
GetComponent<SpriteRenderer>().flipX = (vx < 0);
}
void OnCollisionEnter2D(Collision2D collision)
{
// 만약 충돌한 것의 이름이 목표오브젝트(boy)라면
if(collision.gameObject.name == targetObjectName)
{
showObject.SetActive(true); // 지운것(=비활성화된것)을 다시 표시
Time.timeScale = 0; // 시간을 멈춘다=모든 오브젝트의 움직임을 정지해라
}
}
}