When my turret shoots it first checks to see if the players future position is not obstructed by an object.
It does this by first calculating the future position of the player by taking its current velocity, multiplying it by the time it would take the projectile to reach it, then adding that to the players current position.
Vector3 predictedPosition = target.GetComponent<Velocity>().GetFuturePosition(leadingAccuracy, timeToReachTargetIdeal);
My “shootcheck” object is then placed at this predicted position.
shootCheck.transform.SetPositionAndRotation(predictedPosition, Quaternion.identity);
A raycast is then shot from the projectile origin to the predicted position.
if (Physics.Raycast(origin.position, predictedDeltaDirection, out hit, predictedDeltaMagnitude, shootCheckLayer)) {
Debug.Log(hit.transform.name);
if (hit.transform.CompareTag("ShootCheck")) {
Debug.DrawRay(origin.position, predictedDeltaDirection * hit.distance, Color.green, 10);
Debug.Log("the path is CLEAR");
//Shoot projectile
GameObject o = Instantiate(projectile, origin.position, Quaternion.identity);
//Set velocity of the instantiated projectile object
o.GetComponent<Rigidbody>().velocity = GetPredictiveProjectileVelocity(origin, target, leadingAccuracy, projectileVelocityInitial, spread);
}
else {
Debug.DrawRay(origin.position, predictedDeltaDirection * hit.distance, Color.red, 10);
Debug.Log("the path Is NOT clear");
}
}
else {
Debug.DrawRay(origin.position, predictedDeltaDirection * predictedDeltaMagnitude, Color.blue, 10);
Debug.Log("The raycast missed the object");
}
Now the problem is that the raycast isn’t always detecting a collision with this “shootCheck” object.
Strangely it works when the player is moving parallel away to the direction of the ray but NOT towards.
Gif of walking towards cannon
Gif of walking away from cannon
Gif of walking and running
When strafing it almost never hits when the firerate of the gun is low.
When strafing it hits like 20% of the time when the firerate is high.
Gif of strafing with high firerate.