Choosing speed and direction of AddForce


So I’m making a 2D game in which your character has the ability to push things with a Jedi-like force. I’ve successfully implemented except for one problem: the amount of force (and thus, speed) our character applies on the desired objects is way bigger the farther away they are from each other.

I wish to make it so that the closer an object is to the character, the bigger the force applied is, and the farther away it is, the weaker (so basically, the opposite of what I’m getting).

This is my character’s code:

 Vector2 dir = this.transform.position - go*.transform.position;*

float distance = Vector2.Distance (go*.transform.position, transform.position);*

if (porp == 1)
enemybody.AddForce(dir * (100 - distance));
I inserted that (100 - distance) in hopes of being able to fix it, but alas, ‘dir’ overpowers it.
Is there a way to use AddForce by a) providing a direction, b) providing the speed in which it should travel that direction?
Thank you!

Sounds like you want the force to be inversely proportional to the distance. Two common functions are inverse-linear and inverse-squared.

A more realistic approach is to use the inverse-squared for forces though.

Here’s an example script that should get you going on this:

using UnityEngine;

public class DistanceCheck : MonoBehaviour
	public Transform Obj1;
	public Transform Obj2;
	public float forceSize = 10.0f;

	void Start ()
		Vector2 direction = Obj2.position - Obj1.position;
		float distance = direction.magnitude;
		direction.Normalize ();

		var invLinearForce = direction * (forceSize / distance);
		var invSquaredForce = direction * (forceSize / (distance * distance));


The above is just an example though. You will have to be careful that you don’t use distance = 0 by clamping it to a value above zero. Note that as it approaches zero, especially with the inverse-squared, the force will get very, very large. Simple clamping of either the force or the distance is one way to achieve this.