Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • 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 WerewoofPrime · Apr 29, 2021 at 01:47 AM · raycastdistancerange

how do I restrict my shooting script's raycast to a certain range?

hello, I have a tower script that allows the object it is attached to to rotate towards the nearest enemy with a certain tag and shoot a raycast at that object. however, I have a problem! the tower will rotate towards the object with the tag on it no matter where it is and will shoot a raycast at that object. I am making a MOBA game (like league of legends or Dota 2) and I need the raycast or the tag detection to have a certain range to it so that the tower will only shoot at the enemy with the tag if the enemy is within its range. please help! here is my script:

 using System.Linq;
 using UnityEngine;
 
 public class Tower : MonoBehaviour
 {
   
     public ParticleSystem MuzzleFlash;
 
     private void Update()
     {
         MuzzleFlash.Play();
     
         var objects = GameObject.FindGameObjectsWithTag("Enemy");
           if (!objects.Any())
             return;
 
         var distances = objects.Select(s => Vector3.Distance(transform.position, s.transform.position)).ToArray();
         var first = distances.First();
         var index = 0;
         var index1 = 0;
         foreach (var distance in distances)
         {
             if (distance < first)
             {
                 index1 = index;
                 break;
             }
             index++;
         }
 
         var target = objects[index1];
         if (target == null)
             return;
 
         var p1 = transform.position;
         var p2 = target.transform.position;
         var position = new Vector3(p2.x, p1.y, p2.z); // does not bend to target
         transform.LookAt(position);
 
 
       
         RaycastHit hit;
         if (Physics.Raycast(transform.position, transform.forward, out hit))
         {
 
             if (hit.collider.gameObject.tag == "Enemy")
             {
 
               
 
                 hit.collider.gameObject.transform.GetComponent<EnemyHealth>().HEALTH -= 1f;
 
             }
         }
 
     }
 
 
 }


Comment
Add comment · Show 1
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 HellsHand · Apr 29, 2021 at 02:35 AM 0
Share

It would be much faster for you to look up the docs on Raycast then wait for an answer:

https://docs.unity3d.com/ScriptReference/Physics.Raycast.html

2 Replies

· Add your reply
  • Sort: 
avatar image
0

Answer by Llama_w_2Ls · Apr 29, 2021 at 06:19 AM

There is the range parameter on a raycast, but I believe that your code would be a lot more efficient if you used Physics.CheckSphere to get all nearby enemies, within a radius, instead of looping through all enemies, and checking the distance. Here's an example:

 public class Tower : MonoBehaviour
 {
     public float Range;
 
     void Update()
     {
         var colliders = Physics.OverlapSphere(transform.position, Range);
         var enemies = colliders.Where(x => x.CompareTag("Enemy"));
 
         if (!enemies.Any())
             return;
 
         // Do your distance checking and tower locking here,
         // with the 'enemies' collection
     }
 }

Also, be wary of Vector3.Distance, because I believe it does sometimes return a negative value.

Comment
Add comment · 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
0

Answer by WerewoofPrime · Apr 29, 2021 at 03:45 PM

hello, llama! I have tried something like this when following a tutorial, ( I was using bullets instead of raycasts at this point) and it did not work because the tower would only shoot one bullet every time an enemy came within its range, and would not shoot at the same target more then once...

Comment
Add comment · 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

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.

Follow this Question

Answers Answers and Comments

166 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

Related Questions

Is Raycast relatived to screen resolution? 1 Answer

Math - calculate position in world space from ray on infinite plane 2 Answers

Picking up rigidbody objects 2 Answers

Get the distance between the origin and HitPoint for Raycast? 1 Answer

Raycast stop at distance 3 Answers


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