Home > Back-end >  Unity2D Problem: Enemy does not shoot but it moves
Unity2D Problem: Enemy does not shoot but it moves

Time:01-28

I have a problem with an enemy on Unity2D. The enemy should run to the player and if it's in the attackRange then it has to attack the enemy with a bullet, but the enemy follows my Player. But there is a problem: The enemy doesn't shoot with the bullet. I changed the code, so when I press a button the enemy attacks too. It worked only with the button.

Here's my code for the enemy:

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

public class Enemy2 : MonoBehaviour
{

    public Transform target;
    public Transform firePoint;
    public float speed = 200f;
    public float nextWaypointDistance = 3f;

    public float range = 10f; // the range at which the enemy will start moving towards the player
    public float attackRange = 8f; // the range at which the enemy will attack the player
    float distance;
    public Transform enemyGFX;
    private Transform player; // reference to the player's transform
    public GameObject EnemyWeapon;

    Path path;
    int currentWaypoint = 0;
    bool reachedEndOfPath = false;

    Seeker seeker;
    Rigidbody2D rb;
    public Animator animator;
    bool Stop = false;
    public static float Enemy2Direction;

    // Start is called before the first frame update
    void Start()
    {
        seeker = GetComponent<Seeker>();
        rb = GetComponent<Rigidbody2D>();
        animator = GetComponentInChildren<Animator>();
        player = GameObject.FindGameObjectWithTag("Player").transform;


        InvokeRepeating("UpdatePath", 0f, .5f);
    }

    void UpdatePath()
    {
        if (seeker.IsDone())
        {
            seeker.StartPath(rb.position, target.position, OnPathComplete);
        }
    }

    void OnPathComplete (Path p)
    {
        if (!p.error)
        {
            path = p;
            currentWaypoint = 0;
        }
    }

    // Update is called once per frame
    void FixedUpdate()
    {
        if (Pause.IsPause == false)
        {
            if (path == null)
            {
                return;
            }
            if (currentWaypoint >= path.vectorPath.Count)
            {
                reachedEndOfPath = true;
                return;
            }
            else
            {
                reachedEndOfPath = false;
            }

            Vector2 direction = ((Vector2)path.vectorPath[currentWaypoint] -rb.position).normalized;
            Vector2 force = direction * speed * Time.deltaTime;

            rb.AddForce(force);

            float distance = Vector2.Distance(rb.position, path.vectorPath[currentWaypoint]);

            if (distance < nextWaypointDistance)
            {
                currentWaypoint  ;
            }
            //You can make look it differently, if you delete 'rb.velocity' and add 'force' instead.
            if (rb.velocity.x >= 0.01f)
            {
                enemyGFX.transform.localScale = new Vector3(-1f, 1f, 1f);
                Enemy2Direction = 1f;
            }
            else if (rb.velocity.x <= -0.01f)
            {
                enemyGFX.transform.localScale = new Vector3(1f, 1f, 1f);
                Enemy2Direction = 0f;
            }

            if (distance < attackRange)
            {
                if (Stop = false)
                {
                    StartCoroutine(Attack());
                }
            }
        }

        distance = Vector2.Distance(transform.position, player.position);
        if (distance > range)
        {
            Destroy(gameObject);
        }
        
    }

    void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.tag == "Player")
        {
            animator.SetBool("Damage", true);
        }
        if (collision.gameObject.tag == "Bullet")
        {
            animator.SetBool("Damage", true);
        }
    }
    void Update()
    {
        if (animator.GetBool("Damage"))
        {
            StartCoroutine(DamageAnimation());
        }
        if (Input.GetKeyDown(KeyCode.L))
    {
        StartCoroutine(Attack());
    }
    }

    IEnumerator Attack()
    {
        Debug.Log("Attacked");
        Stop = true;
        yield return new WaitForSeconds(2.0f);
        animator.SetBool("Attack", true);
        Instantiate(EnemyWeapon, firePoint.position, firePoint.rotation);
        yield return new WaitForSeconds(2.0f);
        animator.SetBool("Attack", false);
        StartCoroutine(Wait());
    }

    IEnumerator DamageAnimation()
    {
        yield return new WaitForSeconds(2.0f);
        animator.SetBool("Damage", false);
    }

    IEnumerator Wait()
    {
        yield return new WaitForSeconds(2.0f);
        Stop = false;
    }
}

I don't know what's wrong with my code. Can somebody please help me?

CodePudding user response:

if(Stop == false)

Replace the = in when you check the Stop bool with ==, in C# you use == in order to check for equality

  • Related