• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by jjdoughboy · Apr 30, 2020 at 10:14 PM · collidertower defensecollison

Do I need to attach a Rigidbody to my enemy and/or projectile to get the collisions to work

In my tower defense game I have a turret that will shoot a projectile at the game object with the tag "enemy" and deal damage and destroy itself on collision. my projectile does spawn and heads to the enemy but my enemy's health will decrease before my projectile $$anonymous$$ts the enemy box collider nor will it destroy itself after health decreases. It makes me t$$anonymous$$nk my projectile doesn't recognize the collision or the collider. I should mention my enemy does move following a waypoint system like start at waypoint A and then move to waypoint B. And both my projectile and enemy have box colliders attached to them and neither of them have a Rigidbody attached to them. I've been reading that I need use Rigidbodys but don't know if I need to or how to use them properly so can anyone tell me what I can do to solve t$$anonymous$$s problem.

T$$anonymous$$s is my Projectile script

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 public class Projectile : MonoBehaviour
 {
     private Transform target;
 
     public float speed = 70f;
 
     public GameObject impactEffect;
 
     public int damage = 10;
 
     public float explosionRadius = 0f;
 
     public void Seek(Transform _target)
     {
         target = _target;
     }
 
     // Update is called once per frame
     void Update()
     {
         if (target == null)
         {
             Destroy(gameObject);
             return;
         }
         Vector3 dir = target.position - transform.position;
 
         float distanceT$$anonymous$$sFrame = speed * Time.deltaTime;
 
         if (dir.magnitude <= distanceT$$anonymous$$sFrame)
         {
             HitTarget();
             return;
         }
 
         transform.Translate(dir.normalized * distanceT$$anonymous$$sFrame, Space.World);
 
         transform.LookAt(target);
     }
 
     void HitTarget()
     {
 
         GameObject effectIns = (GameObject)Instantiate(impactEffect, transform.position, transform.rotation);
 
         Destroy(effectIns, 5f);
 
         if(explosionRadius > 0f)
         {
             Explode();
         }
 
         else
         {
             Damage(target);
 
             Destroy(effectIns);
         }
     }
 
     void Explode()
     {
         Collider[] colliders = Physics.OverlapSphere(transform.position, explosionRadius);
 
         foreach(Collider collider in colliders)
         {
             if(collider.tag == "Enemy")
             {
                 Damage(collider.transform);
             }
         }
     }
 
     void Damage(Transform enemy)
     {
         Enemy e = enemy.GetComponent<Enemy>();
 
         if(e != null)
         {
             e.TakeDamage(damage);
         }
 
         
     }
 
 
     void OnDrawGizmosSelected()
     {
         Gizmos.color = Color.red;
 
         Gizmos.DrawWireSphere(transform.position, explosionRadius);
     }
 
 }



T$$anonymous$$s is my enemy script

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 using UnityEngine.UI;
 
 public class Enemy : MonoBehaviour
 {
     public float startSpeed = 10f;
 
     public float speed;
 
     public float startHealth = 200f;
 
     private float health;
 
     public int moneyEarned = 10;
 
     public GameObject deathEffect;
 
     [Header("Health Bar")]
     public Image healthBar;
 
     void Start()
     {
         health = startHealth;
 
         speed = startSpeed;
     }
 
 
     //enemy damage
     public void TakeDamage(float amount)
     {
         health -= amount;
 
         healthBar.fillAmount = health / startHealth;
 
         if (health <= 0)
         {
             Die();
         }
     }
 
 
     public void Slow (float pct)
     {
         speed = startSpeed * (1 - pct); 
     }
 
 
     void Die()
     {
         GameObject audioManagerObject = GameObject.Find("AudioManager");
         AudioManager audioManagerScript = audioManagerObject.GetComponent<AudioManager>();
         audioManagerScript.PlayEnemyDeath();
 
         //Enemy prefab >> Death effect >> plug in death effect
         GameObject effect = Instantiate(deathEffect, transform.position, Quaternion.identity);
 
         Destroy(effect, 1f);
 
         PlayerStats.Money += moneyEarned;
 
         WaveSpawner.EnemiesAlive--;
 
 
         Destroy(gameObject);
     }
 }


I don't know if t$$anonymous$$s has somet$$anonymous$$ng to do with the problem but t$$anonymous$$s my turret script

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 public class Turret : MonoBehaviour
 {
     // Our target will be the instantiated enemyPrefab
     public Transform target;
     private Enemy targetEnemy;
 
 
     [Header("Bullets")]
     // Range at w$$anonymous$$ch our turrets will detect the enemies
     public float range = 15f;
 
     public float fireRate = 1f;
 
     private float fireCountdown = 0f;
 
     public GameObject projectilePrefab;
 
     [Header("Laser")]
     public bool useLaser = false;
     //Select the GameObject the LineRenderer will interact with >> Add Componet >> Type "LineRenderer"
     public LineRenderer laserRenderer;
 
     public ParticleSystem impactEffect;
 
     public float slowImpact = 0.3f;
 
     public int damageOverTime = 30;
 
     [Header("Unity Setup Fields")]
     // Tag we will assign our enemyPrefab so that the turret can know what to detect
     public string enemyTag = "Enemy";
 
     // Assign t$$anonymous$$s to the head of the turret
     public Transform partToRotate;
     // rate at w$$anonymous$$ch the head will turn
     public float turnSpeed = 10f;
 
     public bool usePartToRotate = false;
 
     public Transform firePoint;
 
     // Start is called before the first frame update
     void Start()
     {
         // Rather than update every frame in Update
         // We can set our UpdateTarget() to call at a given rate
         // in t$$anonymous$$s case, 0.5f
         InvokeRepeating("UpdateTarget", 0f, 0.5f);
     }
 
     void UpdateTarget()
     {
         // Assigns our enemies based on the Enemy Tag
         GameObject[] enemies = GameObject.FindGameObjectsWithTag(enemyTag);
         // As close to our turret as the enemies will get
         float shortestDistance = Mathf.Infinity;
         // Sets nearestEnemy to null until an enemy is wit$$anonymous$$n range
         GameObject nearestEnemy = null;
 
         // Creates the enemy Gameobject inside enemies[]
         foreach (GameObject enemy in enemies)
         {
             // Distance from the turret to enemy
             float distanceToEnemy = Vector3.Distance(transform.position, enemy.transform.position);
 
             if (distanceToEnemy < shortestDistance)
             {
                 shortestDistance = distanceToEnemy;
                 nearestEnemy = enemy;
             }
         }
 
         // Determines the next closest enemy
         if (nearestEnemy != null && shortestDistance <= range)
         {
             // Assigns our enemy as our target
             target = nearestEnemy.transform;
 
             targetEnemy = nearestEnemy.GetComponent<Enemy>();
 
         }
 
         if(shortestDistance > range)
         {
             target = null;
             return;
         }
 
     }
 
 
     // Update is called once per frame
     void Update()
     {
         if (target == null)
         {
             if(useLaser)
             {
                 if (laserRenderer.enabled)
                 laserRenderer.enabled = false;
                 impactEffect.Stop();
             }
             return;
         }
 
         if(usePartToRotate)
         {
             LockOnTarget();
             if (useLaser)
             {
                 Laser();
             }
             else
             {
                 // if time til the last shot is less than or equal to 0
                 // resume shooting + restart fireCountDown
                 if (fireCountdown <= 0)
                 {
                     Shoot();
                     fireCountdown = 1f / fireRate;
                 }
                 // restarts fireCountdown
                 fireCountdown -= Time.deltaTime;
             }
         }
         else
         {
             if (useLaser)
             {
                 Laser();
             }
             else
             {
                 // if time til the last shot is less than or equal to 0
                 // resume shooting + restart fireCountDown
                 if (fireCountdown <= 0)
                 {
                     Shoot();
                     fireCountdown = 1f / fireRate;
                 }
             }
             // restarts fireCountdown
             fireCountdown -= Time.deltaTime;
         }
     }
 
     void LockOnTarget()
     {
 
         // In the next few lines, we will tell our turret head to turn towards
         // the enemy it is currently closest to
         Vector3 dir = target.position - transform.position;
 
         Quaternion lookRotation = Quaternion.LookRotation(dir);
 
         Vector3 rotation = Quaternion.Lerp(partToRotate.rotation, lookRotation, Time.deltaTime * turnSpeed).eulerAngles;
 
         partToRotate.rotation = Quaternion.Euler(0f, rotation.y, 0f);
 
     }
 
     void Laser()
     {
         targetEnemy.Slow(slowImpact);
         targetEnemy.TakeDamage(damageOverTime * Time.deltaTime);
 
 
         if (!laserRenderer.enabled)
         {
             laserRenderer.enabled = true;
 
             impactEffect.Play();
         }
 
         laserRenderer.SetPosition(0, firePoint.position);
 
         laserRenderer.SetPosition(1, target.position);
 
         Vector3 dir = firePoint.position - target.position;
 
         impactEffect.transform.position = target.position + dir.normalized * 0.5f;
 
         impactEffect.transform.rotation = Quaternion.LookRotation(dir);
 
     }
 
     void Shoot()
     {
         GameObject bullet60 = (GameObject)Instantiate(projectilePrefab, firePoint.position, firePoint.rotation);
 
         Projectile projectile = bullet60.GetComponent<Projectile>();
 
         if (projectile != null)
         {
             projectile.Seek(target);
         }
 
         GameObject audioManagerObject = GameObject.Find("AudioManager");
         AudioManager audioManagerScript = audioManagerObject.GetComponent<AudioManager>();
         audioManagerScript.PlayFriendlyProjectile();
     }
 
 
     // Creates a visual representation of the range on our turret
     private void OnDrawGizmosSelected()
     {
         Gizmos.color = Color.blue;
 
         Gizmos.DrawWireSphere(transform.position, range);
     }
 }




 
Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

1 Reply

· Add your reply
  • Sort: 
avatar image
0

Answer by cam74 · Apr 30, 2020 at 10:36 PM

Use raycasting!! Colliders and rigid body detection lead to so many detection problems because of the physicsupdate time. Go in unity documentation and look for Raycast, you'll find a perfectly working example that will perfectly fit to your project. If you need help about raycasting just ask again here.

Comment
Add comment · Show 2 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image shuskry · Mar 31, 2021 at 05:09 PM 0
Share

Raycast is good if you have instant projectil , like bullet. but if your projectil can move during 1-2 second to get the target, I don't think that is the best option...

I'm also trying to search the good method for that :)

avatar image HellsHand · Mar 31, 2021 at 05:50 PM 0
Share

On a second note, it looks as if the they are trying to get the collision of an explosion radius and not a single point of contact.

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

168 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Colliders overlapping 2 Answers

I'm working on a tower defense game and my "enemy" game object is losing health before my "projectile" hits the box collider 3 Answers

Connecting Pipes at points 2 Answers

How to recheck collision? 1 Answer

Internal collisions 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges