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;
}
}
}
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.