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