0
votes
using UnityEngine;
using System.Collections;

public class AIEnemy : MonoBehaviour {
   public GameObject bullet;
  public float bulletSpeed = 10;

  public Transform player;

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void FixedUpdate () {


    }
 void OnTriggerStay2D(Collider2D col)
    {
        if(col.tag == "Player")
       {
           // Debug.DrawRay(transform.position, player.position - transform.position);
          RaycastHit2D rhit2d = Physics2D.Raycast(transform.position, player.position - transform.position, Mathf.Infinity);
          if (rhit2d.collider.tag == "Player")
            {
             var clone = Instantiate(bullet, transform.position, Quaternion.identity) as Rigidbody2D;
            clone.velocity = (player.position - transform.position * bulletSpeed);
          }
        }
    }
}

So this is my code. When the player stays in the trigger collider it will find the player and fire at it. But my problem is that the bullet doesn't go towards the player it just falls down. I have set the bullet as a trigger so that isn't the problem. (It's a 2D game btw) The project is on Github: https://github.com/Massaxe/2D-AI/

1

1 Answers

2
votes

One issue I see right away is related to the fact that the bullet is of type GameObject. I am going to assume this GameObject reference is a prefab you have built and linked to the AIEnemy instance. The key thing to note here, is a GameObject usually acts as a container for one to many Component instances, Rigidbody2D being one itself. The following code is what I would use to access the Rigidbody2D component:

var clone = Instantiate(bullet, transform.position, Quaternion.identity) as GameObject;
var rigidBody = clone.GetComponent<Rigidbody2D>();
rigidBody.velocity = (player.position - transform.position * bulletSpeed);

As for the math, I would calculate the velocity like so:

var vel = player.position - transform.position;
vel.Normalize();
vel *= bulletSpeed;
rigidBody.velocity = vel;

What this does, is it calculates the vector between the 2 positions, but, prior to applying the bullet speed, it normalizes the vector (meaning, the vector will have a magnitude of 1, but maintain the appropriate direction). Then, the bullet speed is applied to the normalized vector.

To further expand on this, I would like to note that, if the bullet is falling on its own, there is most likely a 2D gravitational force being applied to the bullet, which may or may not be what you are looking for. In addition, the drag coefficient should also be checked, as if it is any value greater than 0, it will cause the bullet to slow down over time (think of it as friction).