Alex Petrov
Alex Petrov

Reputation: 1

My idea is to make the bullet, which is fired by the player, follow the enemy

So as previously said I need the bullet to follow the enemy. I'm making a 2d Game and just can't figure out how. I'll appreciate it if someone could help me. Here are my scripts.

Bullet Script

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

public class PlayerFire : MonoBehaviour
{
    float moveSpeed = 25f;

    Rigidbody2D rb;

    Monster target;
    Vector2 moveDirection;

    public float firespeed;
    // Start is called before the first frame update
    void Start()
    {
    }

    // Update is called once per frame
    void Update()
    {
        transform.Translate(Vector2.right * firespeed * Time.deltaTime, Space.Self);
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        Debug.Log(collision.transform.name);
        Destroy(gameObject);
    }
}

Enemy script

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

public class Monster : MonoBehaviour {

[SerializeField]
GameObject bullet;

float fireRate;
float nextFire;

public Image BosshealthBar;
public float BosshealthAmount = 100;
public GameObject effect;

// Use this for initialization
void Start () {
    fireRate = 1f;
    nextFire = Time.time;
}

// Update is called once per frame
void Update () {
    CheckIfTimeToFire ();
    
    if (BosshealthAmount <= 0)
    {
        Destroy(gameObject);
    }
}

void CheckIfTimeToFire()
{
    if (Time.time > nextFire) {
        Instantiate (bullet, transform.position, Quaternion.identity);
        nextFire = Time.time + fireRate;
    }
    
}

public void TakeDamage(float Damage)
{
    BosshealthAmount -= Damage;
    BosshealthBar.fillAmount = BosshealthAmount / 100;
}

public void Healing(float healPoints)
{
    BosshealthAmount += healPoints;
    BosshealthAmount = Mathf.Clamp(BosshealthAmount, 0, 100);

    BosshealthBar.fillAmount = BosshealthAmount / 100;
}

void OnCollisionEnter2D(Collision2D col)
{
    if (col.gameObject.tag.Equals("BulletPlayer"))
    {
        TakeDamage(10);
        Instantiate(effect, transform.position, Quaternion.identity);
    }
}
}

Upvotes: 0

Views: 44

Answers (1)

Valon Cazimi
Valon Cazimi

Reputation: 49

Something like this may help u

Vector3 direction = Target.position - Bullet.position;
float distance = direction.magnitude;
float TargetSpeed = 5
Vector3 Force = direction.normalized * ForceMagnitude;
Bullet.AddForce(Force);

But you will need to add it in yourself since i can't tell how your code speceficly works

Upvotes: 1

Related Questions