유니티

[유니티 2D] 플레이어 따라오기

labj 2024. 3. 10. 03:29

게임오브젝트가 플레이어를 따라오도록 합니다. 

* Rotate.cs

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

public class Rotate : MonoBehaviour
{
    public GameObject target;

    private void 
        OnCollisionEnter2D(Collision2D collision)
    {
        if(collision.gameObject.tag == "Bullet")
        {
            transform.position =
                new Vector3(
                    transform.position.x + 1,
                    0,
                    0
                    );
        }
    }

    void Start()
    {        
    }

    void Update()
    {
        Vector3 dir = target.transform.position - transform.position;
        float angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
        Quaternion r = Quaternion.AngleAxis(angle, Vector3.forward);
        transform.rotation = r;
        transform.position = Vector3.MoveTowards(
                transform.position,
                target.transform.position,
                0.01f
            );

    }
}