moving a rigid body toward a static object

I am trying to move a rigid body toward a static object in the middle of the screen automatically.

Using Vector3.Angle I have managed to write a script that prints the angle around Y at which my rigidbody’s Z axis is away from the static object.

Now I have that data im not sure how to apply this angle to an AddForce function to get my desired force direction.

(Basically I dont know how to tell unity I want it to push my rigidbody toward my static object no matter where the rigidbody is on the screen)

Thanks.

You need two things:

  1. Rotate your rigidbody towards the static object. For that you can use transform.LookAt(worldPositionOfStaticObject) on the rigidbody. This will rotate the rigibody so that the forward vector will be pointed towards the static object. Note, that you might need to take in account the up vector you wish to rotate the rigidbody by. If the rigidbody is always perpendicular to the ZX plane of your game world, this will be Vector3.up.
  2. Move the rigidbody along the forward vector. To do that you can just add the rigidbody’s forward vector to the current position of the rigidbody:
    transform.position = transform.position + transform.forward * moveFactor;
    moveFactor is just a name for a float variable which decides how much you wish to move each step.
    If it is constant each frame - the speed you are moving is constant.
    If you keep changing it you are producing an acceleration and deceleration effect.

I appreitiate the quick response, however the ‘LookAt’ function is not something I can use. This is because although I only used 1 static object in the description above, there may actually be several in my scene at one time, each of which gives a small force to the rigidbody object. (Similar to an asteroid moving close to planets in space).

Therefore I need to either be able to pull the object toward the static using a force, or push the rigidbody itself towards a static regardless of the way the the rigidbody is facing.

static object position minus the rigidbody position will give you the direction vector you need. You can normalize it before doing:

transform.position = transform.position + direction * moveFactor;

ahhh I think I understand.

Thank you.

Will give it another go.

Let me know it it works man.

So yeah it worked an absolute treat.

I’d forgotten that transform.position is actually a vector and you can work out directionality between objects.

Once I read your posts again I realised this and now I can have mutiple static objects effecting the single rigidbody at one time.

Thank you very much.

Great man! glad I could help.