Spherecast not always returning hits when it should?

In the game I’m working on I have a beam-type weapon, where the beam is pretty large. I assumed the best way to do this would be a spherecast but it only seems to function about 2/3 of the time it should be. It will clearly be colliding with objects, over the course of up to a second, before it registers a hit on the Spherecast (running on FixedUpdate).
Theres really not much to what I’m doing, but just in case…

public float Distance=20;
public float ExtendSpeed=10;
public float Width=2.5f;
public LayerMask HitMask = new LayerMask();
public Vector3 endPos;

void FixedUpdate(){
	endPos = Vector3.Lerp(endPos,transform.position+(Vector3.forward*Distance),Time.deltaTime*ExtendSpeed);
	endPos.x = transform.position.x;
	
	Ray ray = new Ray(transform.position,endPos);
	RaycastHit hit;
	if(Physics.SphereCast(ray,Width,out hit,Distance,HitMask)){
		HitObject(hit.collider.gameObject);
		updateTimer=0;
		endPos.z = hit.point.z + 1;
	}
}

void HitObject(GameObject hit){
	Debug.Log("I hit a '" + hit.name + "'!");
}

And yes, the LayerMask is set up properly. I mostly only have one so the spherecast doesn’t hit the player object at all.
Thanks for anything you guys can help with!

1 Answer

1

A Ray is a position and a direction. You are using two positions to construct your ray. I assume you are using Lerp() so that the beam happens over time rather than all at once. But your use of Lerp() here will produce an eased movement, so your calculation will dramatically slow and potentially take a lot more time than you anticipate to get near the final position. You can fix this by changing to MoveTowards(). But the reality is you are producing some sort of strange sweep rather than a beam. And since ‘Distance’ remain constant, you are not shooting over time. To figure out what is going on add this at Line 10:

Debug.DrawRay(transform.position, endPos * Distance); 

And I’m not sure why you have this line:

endPos.x = transform.position.x;

Vector3.forward() is (0,0,1), so it will not change the ‘x’ position of your beam, so as far as I can see, this line is a no-op.

Finally make sure the leading edge of your spherecast starts inside your character.

This is a snippet from some much larger code, hence why the question was centric to ShpereCasts and not my logic. I'm AM using/expecting a sweeping motion which is why I'm using a Lerp. I didn't realize that with the Ray though, I'll adjust my code and get back to you. Thanks!

–

I'm not sure of your sweeping calculations, but if everything else is okay, then all you need to do is subtract transform.position from endPos to get your direction vector for the ray.

–