Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice

Bug Enemy doesnt chase players current position

Discussion in 'Scripting' started by Rupruk, Mar 30, 2024.

  1. Rupruk

    Rupruk

    Joined:
    Feb 17, 2024
    Posts:
    1
    So i made a WaveSpawner that spawns in enemies every 10-15 seconds but the enemies that spawn in go to the position 0,0 and not my player position. Help me fix it please.

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


    public class AImovement : MonoBehaviour
    {
    public GameObject player;
    public float speed;
    private float _distance;
    public float distanceBetween = 10f;
    private void Update()
    {
    _distance = Vector2.Distance(transform.position, player.transform.position);
    Vector2 direction = player.transform.position - transform.position;
    direction.Normalize();
    float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;

    if (_distance < distanceBetween)
    {
    transform.position = Vector2.MoveTowards(transform.position, player.transform.position, speed * Time.deltaTime);
    transform.rotation = Quaternion.Euler(Vector3.forward * angle);
    }
    }


    }
     
  2. ArachnidAnimal

    ArachnidAnimal

    Joined:
    Mar 3, 2015
    Posts:
    1,936
    Nowhere in your code you posted are you moving the AI if _distance > distanceBetween

    You're using Vector2. Did you try the code using Vector3 instead to see if you get the results you expect?
     
    Last edited: Mar 30, 2024