Home > OS >  changing transform.position never equal to transform.position transform.forward
changing transform.position never equal to transform.position transform.forward

Time:12-05

I am creating a basic shooting mechanism, where the bullet ends at the end of a LineRenderer. My code for the instantiated bullet is as follows:

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

public class BulletScript : MonoBehaviour
{
    [SerializeField] PlayerAttacking PA;
    [SerializeField] float speed;
    Vector3 BulletEndDist;

    // Start is called before the first frame update
    void Start() {
        PA = GameObject.Find("AttackTrail").GetComponent<PlayerAttacking>();
        BulletEndDist = transform.position   (transform.forward * PA.TrailDistance) ;
    }

    // Update is called once per frame
    void Update() {
        if(transform.position == BulletEndDist)
        {
            Destroy(this.gameObject);
        }
        transform.Translate(new Vector3(0, 0, speed));
    }

    private void OnCollisionEnter(Collision collision) {
        if(collision.transform.tag == "Enemy")
        {
            // Decrease health
            Destroy(this.gameObject);
        }
        else
        {
            Destroy(this.gameObject);
        }
    }
}

The problem I am getting is the bullet never gets destroyed, and through some Debug.Logs I found its not entering the if condition in the Update. This makes no sense as surely the bullet should get to BulletEndDist eventually? Please help!

CodePudding user response:

If you want to check for the distance of the bullet from the player, you should use the Vector3.Distance function, to calculate the distance into a float, that you can compare to the maximum distanse you want the bullet to be from the player.

  • Related