4
using UnityEngine;    
using System.Collections;
using System;

public class TurretScript : MonoBehaviour
{

    public float rangeToPlayer;
    public GameObject bullet;
    // public GameObject spherePrefab; 
    private GameObject player; // Tag for DynamicWaypointSeek
    private bool firing = false;  //Firing status
    private float fireTime;     // Fire Time
    private float coolDown = 1.00F;  // Time to cool down fire
    private int health = 5; //Health of turret 
    private bool bDead;
    private Action cur;

    void Start()
    {
        player = GameObject.FindWithTag("Player");
        bDead = false;
    }



    void Update()
    {
        if (PlayerInRange())
        {     // PlayerInRange is bool function defined at the end
            transform.LookAt(player.transform.position); //Rotates the transform (weapon) so the forward vector points at /target (Player)/'s current position
            RaycastHit hit;
            if (Physics.SphereCast(transform.position, 0.5F, transform.TransformDirection(Vector3.forward), out hit))
            {  //The center of the sphere at the start of the sweep,The radius of the sphere,The direction into which to sweep the sphere.
                if (hit.transform.gameObject.tag == "Player")
                { //information in hit (only interested in "Player")
                    if (firing == false)
                    {
                        firing = true;
                        fireTime = Time.time; //keep the current time
                        GameObject bul;
                        Quaternion leadRot = Quaternion.LookRotation(player.transform.position); //Calculate the angular direction of "Player";   
                        bul = Instantiate(bullet, transform.position, leadRot) as GameObject;  // existing object to be copied, Position of Copy, Orientation of Copy
                        //Destroy(bullet, 2.0f); 
                    }
                }
            }
        }
        if (firing && fireTime + coolDown <= Time.time) // prvious time stored in fireTime + cool down time is less --> means the firing must be turn off
            firing = false;
       // Destroy(GameObject.FindGameObjectWithTag("Bullet")); 

        if (health <= 0)
            cur = Deadstate;


    }

    protected void Deadstate()
    {
        if (!bDead)
        {
            bDead = true;
            Explode();
        }
    }

    void Explode()
    {
        Destroy(gameObject, 1.5f);
        
    }


    bool PlayerInRange()
    {
        return (Vector3.Distance(player.transform.position, transform.position) <= rangeToPlayer); //Vector3.Distance(a,b) is the same as (a-b).magnitude.
    }

    void OnTriggerEnter(Collider col)
    {
        HealthBarScript.health -= 10f;

    }
 }

This is code I wrote for a enemy turret in my current unity project. The idea is that it will fire a bullet at the player once it's in range and stop when it's out of range and when the bullet collides with the player, the player will take damage, but I'm struggling to figure out why the bullet won't do any damage. Thoughts? Very much appreciate the help!

Jay
  • 2,553
  • 3
  • 17
  • 37
  • Are you sure that this is C++, and not Java? This has to be the weirdest looking C++ code that I ever saw. – Sam Varshavchik Dec 12 '18 at 01:44
  • 3
    Its neither c++ or Java. That is C#. – Dayan Dec 12 '18 at 01:49
  • No idea why, this is the code for the turret, show us the code for the player where he is suppose to take damage. – AresCaelum Dec 12 '18 at 01:52
  • `void OnTriggerBullet(Collision coll) { if(coll.gameObject.tag.Equals ("Bullet")) { Destroy(gameObject); } UnityEngine.SceneManagement.SceneManager.LoadScene(levelToLoad); } ` This is part in my player script where my player encounters the bullet. The idea is that if the player gets hit with the bullet, the player is destroyed and triggers the game over screen. – MadDog Gaming Dec 12 '18 at 02:08
  • 1
    Possible duplicate of [Collision Detection for fast moving game object in Unity](https://stackoverflow.com/questions/44266691/collision-detection-for-fast-moving-game-object-in-unity) – derHugo Dec 12 '18 at 06:42
  • Some workaround would be to add a BoxCollider(2D if its a 2D game) and set to be a trigger and then do something in `OnTriggerCollide(2D)` – jeuxjeux20 Dec 12 '18 at 11:24

1 Answers1

0

According to my experience: bullet speed may be too fast to detect collision.
Imagine that in 2d:
frame 1:
.BB.......OOO......
frame 2:
........BBOOO......
frame 3:
..........OOO..BB..
Where OOO is your object and BB is your bullet.

To fix this you can have a bigger collider for the bullet. Other workaround like "dynamic" collider are also possible.

  • There's also the raycasting technique where you check the space in front of the object the distance it is moving to check for obstacles – Eliasar Dec 12 '18 at 15:38