Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 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 Dragonfly3r · Nov 18, 2016 at 07:43 AM · c#collisionraycastflashlightcone

Create interchanging Raycast cone for flashlight

So I'm creating a flashlight with 2 modes: Low intensity & high intensity

Low intensity mode gives a smaller range with a large cone of light and drains battery slowly High intensity mode gives a large range but with a narrow cone of light and drains battery fast

I want to make a raycast in the form of that cone of light so then I can create my collisions with enemy AI. However I have no clue as to how I can produce said raycast cone. Does anyone know how to do this / point me in the right direction?

This ray cast cone would of course change size depending on which intensity mode the flashlight was in so if high intensity mode then it'll be a narrow cone shape with a long range whilst in low intensity mode the raycast cone would be a very wide cone shape with a short range

Code for flashlight script is as below:

 private Light flashlight;
     //public AudioClip _switch;
    // public AudioClip _batteryPickUp;
 
     public int _maximumBatteryPower = 100;
     public float _currentBatteryPower = 0f;
 
     // 2 Modes of flashlight Low = small intensity short range, large angle. High = large intensity, small angle but longer range.
 
     public float _lowPowerIntensityMode = 3f;
     public float _lowPowerSpotAngle = 40f;
     public float _lowPowerRange = 20f;
 
     public float _highPowerIntensityMode = 6f;
     public float _highPowerSpotAngle = 20;
     public float _highPowerRange = 30f;
 
     public float _lowDrainBatterySpeed = 2.5f;
     public float _highDrainBatterySpeed = 5f;
 
     public float _batteryBarLength;
 
     public float _maxFlickerSpeed = 1f;
     public float _minFlickerSpeed = 0.1f;
 
     // Use this for initialization
     void Start()
     { flashlight = GetComponentInChildren<Light>();
         flashlight.enabled = false;
         _currentBatteryPower = _maximumBatteryPower; }
     
     // Update is called once per frame
     void Update ()
     { _batteryBarLength = (Screen.width / 4) * (_currentBatteryPower / (float) _maximumBatteryPower);
 
        // if (Input.GetButtonDown("Flashlight"))
       //  { //GetComponent<AudioSource>().PlayOneShot(_switch);
             //flashlight.enabled = !flashlight.enabled; }
 
         if (flashlight.enabled)
         { FlashlightOn(); }
 
         if (_currentBatteryPower == 0)
         { StopCoroutine("FlashlightModifier");
             flashlight.enabled = false; }}
 
     private void FlashlightOn()
     { if (Input.GetMouseButton(1) && flashlight.enabled == true)
         { flashlight.intensity = _highPowerIntensityMode;
             flashlight.spotAngle = _highPowerSpotAngle;
             flashlight.range = _highPowerRange; }
         else
         { flashlight.intensity = _lowPowerIntensityMode;
             flashlight.spotAngle = _lowPowerSpotAngle;
             flashlight.range = _lowPowerRange; }
 
         if (flashlight.enabled)
         { _currentBatteryPower -= _lowDrainBatterySpeed * Time.deltaTime; }
 
         if (Input.GetMouseButton(1) && flashlight.enabled == true)
         { _currentBatteryPower -= _highDrainBatterySpeed * Time.deltaTime; }
 
         if(_currentBatteryPower <= 0)
         { _currentBatteryPower = 0; }
 
         if (_currentBatteryPower < 10)
         { StartCoroutine("FlashlightModifier"); }
 
         if (_currentBatteryPower > 10)
         { StopCoroutine("FlashlightModifier"); }}
 
     IEnumerator FlashlightModifier()
     { while (true)
         { flashlight.enabled = true;
             yield return new WaitForSeconds
                 (Random.Range(_minFlickerSpeed, _maxFlickerSpeed));
 
             flashlight.enabled = false;
             yield return new WaitForSeconds
                 (Random.Range(_minFlickerSpeed, _maxFlickerSpeed)); }}
     
     public void AddBattery(int _batteryPowerAmount)
     { _currentBatteryPower += _batteryPowerAmount;
 
         if (_currentBatteryPower >= _maximumBatteryPower)
         { _currentBatteryPower = _maximumBatteryPower; }
 
         // if (_batteryPickUp != null)
         //{ GetComponent<AudioSource>().clip = _batteryPickUp;
         //  GetComponent<AudioSource>().Play(); }}
 
         //void OnGUI()           // Change this to latest GUI in unity
         //{ GUI.Box(new Rect(5, 35, _batteryBarLength, 20), "Battery"); 
     }
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

2 Replies

· Add your reply
  • Sort: 
avatar image
0
Best Answer

Answer by Dragonfly3r · Dec 03, 2016 at 10:40 PM

I ended up fixing this myself. I 2 cone shapes in 3ds max. Removed the mesh renderer and mesh filter and turn the mesh collider into convex & istrigger.

In the code this is what I changed:

 void Start()
     { flashlight = GetComponentInChildren<Light>();
         _lowIntensityBeam.GetComponent<GameObject>();
         _highIntensityBeam.GetComponent<GameObject>();
         _lowIntensityBeam.gameObject.SetActive(false);
         _highIntensityBeam.gameObject.SetActive(false);
 
         flashlight.enabled = false;
         _currentBatteryPower = _maximumBatteryPower; }

Void Update additions:

  if (flashlight.enabled)
         { FlashlightOn();
             if (_modeChange == false)
             {
                 _lowIntensityBeam.gameObject.SetActive(true);
                 _currentBatteryPower -= _lowDrainBatterySpeed * Time.deltaTime;
             }
             else if (_modeChange == true)
             {
                 _currentBatteryPower -= _highDrainBatterySpeed * Time.deltaTime;
             }
         }
 
         else if (!flashlight.enabled)
         {
             _lowIntensityBeam.gameObject.SetActive(false);
             _highIntensityBeam.gameObject.SetActive(false);
             _modeChange = false;
         }
 
         if (_currentBatteryPower == 0)
         { StopCoroutine("FlashlightModifier");
             flashlight.enabled = false;
             _lowIntensityBeam.gameObject.SetActive(false);
             _highIntensityBeam.gameObject.SetActive(false);
         } }
 
     private void FlashlightOn()
     { if (flashlight.enabled)
         {
             if (Input.GetMouseButtonDown(1) && _modeChange == false)
             {
                 _modeChange = true;
                 flashlight.intensity = _highPowerIntensityMode;
                 flashlight.spotAngle = _highPowerSpotAngle;
                 flashlight.range = _highPowerRange;
                  _lowIntensityBeam.gameObject.SetActive(false);
                 _highIntensityBeam.gameObject.SetActive(true);
                 
             }
             else if (Input.GetMouseButtonDown(1) && _modeChange == true)
             {
                 _modeChange = false;
                 flashlight.intensity = _lowPowerIntensityMode;
                 flashlight.spotAngle = _lowPowerSpotAngle;
                 flashlight.range = _lowPowerRange;
                 _lowIntensityBeam.gameObject.SetActive(true);
                 _highIntensityBeam.gameObject.SetActive(false);
                 
             }
         }
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 ElijahShadbolt · Nov 18, 2016 at 09:36 AM

You could loop through all your AIs that you want to test for Line of Sight in the cone, and check that the angle between the light's forward vector and the direction towards the AI is smaller than the SpotAngle you set, as well as that the AI is within a range. Then you could loop through each of those AIs and raycast towards the flashlight from their position to see if they indeed have Line of Sight.

LightLineOfSight.cs - attach to your flashlight (spot light)

 using UnityEngine;
 
 public class LightLineOfSight : MonoBehaviour
 {
     public GameObject[] targetAIs;
 
     void Update()
     {
         Light flashlight = GetComponent<Light>();
         if (flashlight == null)
             return;
         
         foreach (GameObject target in targetAIs)
         {
             Vector3 point = target.transform.position;
             Vector3 direction = point - transform.position;
 
             // if within range and cone angle
             if (direction.magnitude <= flashlight.range && Vector3.Angle(transform.forward, direction) <= flashlight.spotAngle/2)
             {
                 Debug.Log(target.name + " is in the light!");
 
                 Ray ray = new Ray(point, -direction);
                 RaycastHit[] hits = Physics.RaycastAll(ray, flashlight.range);
 
                 bool foundHit = false;
                 foreach (RaycastHit hit in hits)
                 {
                     if (hit.transform != transform && hit.transform != target.transform) // if not the flashlight nor that AI
                     {
                         Debug.Log("There is something between the flashlight and " + target.name);
                         foundHit = true;
                         break;
                     }
                 }
                 if (!foundHit)
                 {
                     Debug.Log(target.name + " has direct line of sight to the flashlight.");
                 }
             }
         }
     }
 }
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

5 People are following this question.

avatar image avatar image avatar image avatar image avatar image

Related Questions

Align to grid in runtime problem 1 Answer

How to check if a raycast is not hitting any tagged colliders? 0 Answers

Raycast doesnt detect object in front of rigidbody (player is stuck on wall) 1 Answer

Can't Make Raycast Target Nearest Character 1 Answer

Raycast won't fire 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