Sphere cast problem

I am having problems with sphere cast.

I am using it to move a sphere across a scene, and if it hits a box collider move it to that location.

The problem I am having is that I can end up inside objects. This only happens when I am moving quickly (when gravityAmount is high.)

I have checked that I am not starting from within the object but I still hit the ‘Bad News’ debug line.

The problem is intermittent and I cannot replicate it everytime so the Time.deltaTime variable is possibly playing a part.

Any help would be vey welcome.

void UpdateFalling ()
	{
                int layerMask = 1 << 8;

                //gravityAmount is a class variable (float)
		gravityAmount = Mathf.Min (maxGravityAmount, gravityAmount + (Time.deltaTime * gravitySmooth));
		
		RaycastHit hitInfo;
		
		if (Physics.SphereCast(transform.position, 20.0f, gravityVector, 
			out hitInfo, gravityAmount, layerMask))
		{
			//Do something with hitInfo
		}
		else
		{
                        //We can move to the position
			transform.position = transform.position + (gravityAmount * gravityVector);

                        //Check we have not somehow collided.
                        if (Physics.CheckSphere(transform.position, 20.0f, layerMask))
                        {
                                 Debug.LogError("Bad news");
                        }
		}
	}

Are you calling UpdateFalling from FixedUpdate? Physics code should use FixedUpdate rather than Update.

Thanks Sajidfarooq, I tried this but I’m afraid it did not help.

As I understand it, you need to use FixedUpdate when using RigidBodies and applying forces.

I don’t have a rigidbody attached to to either object involved.

It does seem to only happen if the object being collided with is moving though, but I didn’t think it was possible for another object to move during an method.

When I use Custom collision detection i write my own update methods.

public Awake()
{ 
     StartCoroutine(CoUpdate() );
}
public IEnumerator CoUpdate()
{ 
    while(true)
    {
          //Check Sphere Cast here
          yield return new WaitForSeconds(0.001f); // The faster the better for collision.. should help to never miss. 
    }
}

Even better idea… Make the WaitForSeconds based on how fast the player is traveling… So it can be dynamic checking…

Thanks Ereous. Any chance that you can explain why you need to do this so I can better understand why it’s solving my problem.

Is it just a case of making the update happen more frequently so raising the chance of catching a collision?

I do this for better control. Since I program in C# it allows me to halt updating if I want by simply added in a bool before hand…

if(haltUpdate)
yield return null;

But also as you stated you can control how fast something reacts as well.