유니티 특정물체 바라보기 2D

2020. 6. 29. 21:32유니티실습

반응형

안녕하세요 유니티 비기너입니다.

이번 시간에는 특정물체를 바라보는 방법에 대해 알아보겠습니다.

이전 글에서는 LookAt을 사용하여 물체를 바라보게 하였지만 2D에서는 각도가 회전하게 되면

물체가 보이지 않아 적절하지 않기 때문에 다른 방법을 소개하겠습니다.

 

결과 화면

한 번에 보기

1. 플레이어 오브젝트 생성

2. 적 오브젝트 생성

3. 플레이어 이동 스크립트 작성 및 적용

4. 적 스크립트 작성 및 적용

 

1. 플레이어 오브젝트 생성

위치에 따라 회전하는 것을 보여줘야 하기 때문에 이동 스크립트를 포함시킬 플레이어 오브젝트 생성

2. 적 오브젝트 생성

플레이어를 위치를 바라볼 적 오브젝트 생성

3. 플레이어 이동 스크립트 작성 및 적용

public class PlayerManager : MonoBehaviour {

    public Rigidbody2D rb;
    public float moveSpeed;

    void Update() {
        if (Input.GetMouseButton(0)) {
            Vector3 mpos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            Vector3 direction = (mpos - transform.position).normalized;
            rb.velocity = new Vector2(direction.x * moveSpeed, direction.y * moveSpeed);
        } else if (Input.GetMouseButtonUp(0)) {
            rb.velocity = Vector2.zero;
        }
    }
}

 

클릭이 발생하고 유지되는 지점으로 플레이어가 이동하는 스크립트입니다.

 

4. 적 스크립트 작성 및 적용

public class Enemy : MonoBehaviour {

    public int rotateSpeed;
    public Transform target;

    void Update() {
        if (target != null) {         
            Vector2 direction = new Vector2(
                transform.position.x - target.position.x,
                transform.position.y - target.position.y
            );

            float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
            Quaternion angleAxis = Quaternion.AngleAxis(angle - 90f, Vector3.forward);
            Quaternion rotation = Quaternion.Slerp(transform.rotation, angleAxis, rotateSpeed * Time.deltaTime);
            transform.rotation = rotation;
        }
    }
}

 

 

우선적으로 백터의 뺄셈을 활용하여 적 오브젝트가, 플레이어 오브젝트를 바라보는 방향을 구하고

Mathf Atan2와, Mathf Rad2 Deg를 활용하여 각도 값을 구하여 값만큼 회전시켜 플레이어를 바라보게 하는 내용입니다.

 

 

반응형