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!
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!
– keyp3rI'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.
– robertbu