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 Serreas · Dec 30, 2017 at 03:04 PM · arrayfor loopraycastall

Problem with raycasts in a for loop

Hi all,

so I'm currently working on my own hit detection system for my third person melee controller. First here is the code I've developed.

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 public class HitDetection : MonoBehaviour
 {
     [Header("- Hit Detection Markers - ")]
     //public GameObject[] allmarkers;
     public Transform[] markers;
     public bool DebugRaycasts ;
 
     [Header("- Hit Layer -")]
     public LayerMask hitLayer;
    
     [Header("- Test Values -")]
     public float health = 100;
     public float damage = 1;
     public string EnemyTag = "Enemy";
 
     #region Arrays
 
     Vector3[] lastPos;
     Vector3[] currPos;
     Vector3[] dir;
     float[] dist;
     RaycastHit[] hits;
 
     #endregion 
 
     bool hitpoint;
     bool enableDetection;
 
     void Start()
     {
         //allmarkers = GameObject.FindGameObjectsWithTag("Marker");
 
         lastPos = new Vector3[markers.Length];
         currPos = new Vector3[markers.Length];
         dir = new Vector3[markers.Length];
         dist = new float[markers.Length];
     }
 
     void Update()
     {
 
         if (enableDetection)
         {
             
             detectHit();
             applyDamage();
         }
         else
         {
             return;
         }
     }
 
     void detectHit()
     {
 
         for (int i = 0; i < markers.Length; i++)
         {
             Debug.Log(lastPos[i]);
 
             currPos[i] = markers[i].position;
             dir[i] = currPos[i] - lastPos[i];
             dist[i] = Vector3.Distance(currPos[i], lastPos[i]);
 
             if (currPos[i] != lastPos[i] && DebugRaycasts)
             {
                 
                 Debug.DrawRay(lastPos[i], dir[i], Color.white, 0.3f);
             }
 
             hits = Physics.RaycastAll(lastPos[i], dir[i], dist[i], hitLayer);
 
             hitpoint = false;
             for (int i2 = 0; i2 < hits.Length; i2++)
             {
                 
                 if (hits[i2].collider.tag == EnemyTag)
                 {
                     hitpoint = true;
                     
                 }
 
             }
 
             lastPos[i] = currPos[i];
         }
     }
 
 
 
     void applyDamage()
     {
 
         if (hitpoint) 
         {
             health -= damage;
             Debug.Log(health);
             return;
             
         }
     }
 
     void startAttack()
     {
         enableDetection = true;
     }
     void stopAttack()
     {
         enableDetection = false;
     }
 }
 

I'm using a marker hit detection system that casts a ray for each marker based on the marker position in the previous frame (markers are attached to the weapon). This loop also only runs at the specified animation events as can be found at the bottom of the script. Its using a for loop to iterate through each marker and create a ray path for each marker and when it intersects a collider it returns true.

The problem I've found is that in the very first iteration after you click to attack the array "lastPos" doesn't have any values. For example if I use 8 markers for the first iteration all 8 positions in "lastPos" are 0. This causes a bit of a glitch for the debug rays and raycasts where you could be far away on the map and it would cast rays to the 0 location of the map right after you click to attack. I've tried finding a solution for a while now but couldn't come up with any so I'm hoping someone else could help me out with it. Thanks. (sorry for the long post).

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
1
Best Answer

Answer by sparkzbarca · Dec 30, 2017 at 05:55 PM

so it has that because for the first run there is of course no "last pos" to have.

So you dont want to intialize to zero.

Presumably the first iteration should be some i guess small distance from cur pos?

Basically you have to logically explain where the ray should be cast from at frame 0 to start the wave. zero obviously isn't working.

examples might be to just for the first frame make it start at

curpos + a vector in a direction that makes sense to cast from a short distance away.

So for example maybe take the center of the gun model so

gun.transform.position. Then take the vector going in the direction behind so

-gun.transform.position.forward

negative gun.transform.position.forward is backward.

so you now have what direction is behidn teh gun.

you could have the lastpos[i] = curpos[i] - gun.transform.forward;

this would be a special intialize case. so you'd only call that in the start function to initialize the values of the lastpos and from there assign it to curpos.

you'd have to of course first find curpos like you already do but do it in start as well (or make finding cur pos a seperate function and call it once in start and once in your loop later)

so you find curpos then use that to get a set distance away from it that makes since to cast a ray to it and assign those positions to last pos for the first initialze. now your not starting at zero.

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 Serreas · Dec 30, 2017 at 10:28 PM

so I found a bit of a work around that works well enough. In line 46 I added two other condition bools from another script which are button toggles and in lines 81, and 98 I added the enableDetection bool which is activated at certain animation events. So how it works now is once I press the button to draw the weapon it activates the raycasts (which then work fine after the initial first iteration) and then only register hits based on the animation events. Should I find a more proper solution I will update this answer. Thanks for your help though

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

72 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

Related Questions

Method to loop through an unknown number of variable combinations in C# 1 Answer

Order or Sort list of files using DirectoryInfo 1 Answer

[C#] Physics.Raycast returns an array and can't access the length 2 Answers

Loop through array until certain value is found. 2 Answers

Add object on trigger to array, then cast a ray at all objects in the array 0 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