Using RigidBody.addForce to move an object to a point

I’m using this to make some sudo-gravity for my new project. Basically, I need to use addForce to move one object to another. Currently I am doing this:

void Gravitate(GameObject obj){
		Ray dir = new Ray(transform.position, obj.transform.position);
		print (dir.direction);
		if(obj.GetComponent<Rigidbody>()){
			obj.rigidbody.AddForce((-dir.direction)*force);
		}
	}

At first the object (obj) moves toward the object that the script is attached to, but then it moves towards the origin and orbits there. What am I doing wrong?!

That seemed to work at first, but if I move the object that is exerting gravitational force from the origin, any object that comes into contact with the gravity moves to the origin and no to the object exerting the force.

Answer to that problem was found here: http://answers.unity3d.com/questions/175427/adding-force-toward-specific-object.html I needed to change -dir.direction to: (obj.transform.position - transform.position)*-1

2 Answers

2

Adding force doesn’t immediately cancel out existing velocity. Consider a spaceship traveling in a direction. If you apply side thrust in doesn’t make an immediate 90 degree turn.

You can mitigate your problem by upping the ‘drag’ setting on the rigidbody. The higher the setting, the faster it will discard existing velocity. You will need to up the forces added to ship to compensate for the drag to keep the current performance.

An alternate solution is to assign to the Rigidbody.velocity rather than use AddForce(). Assigning to velocity will cause an immediate change in direction. You will hit your target, but at the cost of realistic movement.

You may still have a problem in that most of the time, given the calculations based on a discrete frame rate, you will never hit your target exactly. That is your object and your target will never have exactly the same position. So with either of these two solutions your object will tend to thrash a bit at the destination. The solution will depend on your game mechanic. You can either stop the object when it is within some threshold of the target, or find a new target when it is within the threshold.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class fp : MonoBehaviour
{
public Transform plr;//transform of the gameobject to move to
Vector3 offset;//direction of gameobject to move to
public float offspeed=7;//speed at which to move
public Rigidbody rb;//rigidbody of gameobject to move

void Start()
{
    offset = plr.transform.position - transform.position;//calculating direction and distance
}


void LateUpdate()
{
    rb.AddForce(offset);//applying force
    offset = plr.transform.position - transform.position;//changing the direction to move to if player moves
}

}

hey man dont know y its like this ..