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*);*

currPos = markers*.position;*
dir = currPos - lastPos*;*
dist = Vector3.Distance(currPos_, lastPos*);*_

if (currPos != lastPos && DebugRaycasts)
{

Debug.DrawRay(lastPos_, dir*, Color.white, 0.3f);
}*_

hits = Physics.RaycastAll(lastPos, dir_, dist*, hitLayer);*_

hitpoint = false;
for (int i2 = 0; i2 < hits.Length; i2++)
{

if (hits[i2].collider.tag == EnemyTag)
{
hitpoint = true;

}

}

lastPos = currPos*;*
}
}

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).

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 = curpos - 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.

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