- Home /
Physics.OverlapSphere not including object
Is there something wrong with this code? it seems like it doesn't work as I tend to. I want to pull the object if the object is in the range of sphere, but it seems it's not working Do you have any idea why it isn't working?
public Rigidbody attractedTo;
public Rigidbody IAmGoingTo;
public float strengthOfAttraction;
public float radius = 5f;
float tillNinety = 0;
void FixedUpdate()
{
if (Input.GetKeyDown("e"))
{
Reach();
}
}
void Reach()
{
Collider[] sphereInsideTheZone = Physics.OverlapSphere(transform.position, radius);
foreach (Collider nearbyObject in sphereInsideTheZone)
{
Rigidbody rb = nearbyObject.GetComponent<Rigidbody>();
if (rb != null && gameObject.name != "GravityChangerBomb")
{
Debug.Log(nearbyObject.gameObject.name);
rb.AddForce((rb.transform.position - attractedTo.transform.position) * strengthOfAttraction);
rb.useGravity = true;
}
}
}
Answer by kubajs · Mar 26, 2020 at 10:40 PM
First issue is you read key down in FixedUpdate. This won't occassionally work as Input is only read during Update. If FixedUpdate misses the update timeframe, the input will be missed. Read in Update and cache it to a field and re-use the field later in FixedUpdate when working with Physics.
I see one mistake here. You need to use rb.gameObject:
if (rb != null && rb.gameObject.name != "GravityChangerBomb")
Also, this is not related to this issue but I would rather read rb.position instead of rb.transform.position. Not sure whether rb.transform.position is with sync with rb.position in FixedUpdate. But I might be wrong here.
Whenever you have similar issue like this you reported, I recommend you to debug the code since some mistakes and typos like this are sometimes hard to find and you'll spare a lot of time eventually.
Answer by sychoi461 · Mar 27, 2020 at 05:42 PM
I solved it! if (Input.GetKeyDown("e")) { Reach(); } }
public void Reach()
{
Collider[] sphereInsideTheZone = Physics.OverlapSphere(transform.position, radius);
foreach (Collider nearbyObject in sphereInsideTheZone)
{
Rigidbody rb = nearbyObject.GetComponent<Rigidbody>();
if (nearbyObject.gameObject.tag == "Metal")
{
Debug.Log(nearbyObject.gameObject.name);
rb.transform.Rotate(Vector3.down, turnspeed * Time.deltaTime);
rb.AddForce((attractedTo.transform.position - rb.transform.position) * strengthOfAttraction);
rb.useGravity = true;
// nearbyObject.GetComponent<MeshRenderer>().enabled = false;
}
}
}
It works fine when I use transform.position but I will make a change to it! @kubajs
Your answer
![](https://koobas.hobune.stream/wayback/20220612225827im_/https://answers.unity.com/themes/thub/images/avi.jpg)