Skip to content
Snippets Groups Projects
IAMovement.cs 1.2 KiB
Newer Older
william's avatar
william committed
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class IAMovement : MonoBehaviour
{
    [SerializeField] private Transform targetTransform;
    [SerializeField] private float speed;
    private float offsetDistance;
    private Animator animatorController;

    void Start()
    {
        animatorController = GetComponent<Animator>();
        animatorController.SetBool("Moving", false);
        animatorController.SetBool("Shooting", false);
        animatorController.SetTrigger("DefTurn");

        offsetDistance = (targetTransform.position - transform.position).magnitude + 0.5f;
    }

    private void Update()
    {
        Vector2 displacementFromTarget = targetTransform.position - transform.position;
        Vector2 directionToTarget = displacementFromTarget.normalized;
        Vector2 velocity = directionToTarget * speed;

        float distanceToTarget = displacementFromTarget.magnitude;

        if (distanceToTarget > offsetDistance)
        {
            animatorController.SetBool("Moving", true);
            transform.Translate(velocity * Time.deltaTime);
        }
        else
        {
            animatorController.SetBool("Moving", false);
        }
    }
}