How to set an object's position a certain distance away from a target at the same angle?

I’m trying to have an object stay 3 units away as the characters moves closer towards it so it’s like it gets pushed.

if (Vector2.Distance(transform.position, player.transform.position) < 3)
                {
                    transform.position = ((player.transform.position - transform.position).normalized * 3) + player.transform.position;
                }

This is what I’ve written but it doesn’t work. As you walk into the radius the object will go to the other side rather than being ‘pushed’.

The key to making sure the object is pushed away from the player is to calculate the vector between the object and the player. With that you know which direction to move the object.


Given two points A and B, the vector AB that goes from A to B is calculated as:
AB = (B - A)

or written out:

AB = (u2 - u1, v2 - v1)

Once we know this vector there are a few ways we can proceed. I’ve thrown together a couple different scripts here. The first uses Transform.Translate() and the second uses Rigidbody.AddForce(). They are written for 3D but it should be trivial to convert them to handle 2D if necessary.

Script 1:

#pragma strict

public var player : GameObject;
public var distance : float;
public var pushStrength : float;

function Update()
{
	//Calculate the distance between the object and the player
	var dist = Vector3.Distance(transform.position, player.transform.position);

	if (dist < distance)
	{
		//Calculate the vector between the object and the player
		var dir : Vector3 = transform.position - player.transform.position;
		//Cancel out the vertical difference
		dir.y = 0;
		//Translate the object in the direction of the vector
		transform.Translate(dir.normalized * pushStrength);
	}
}

Script 2:

#pragma strict

@script RequireComponent(Rigidbody);

public var player : GameObject;
public var distance : float;
public var pushStrength : float;

private var rb : Rigidbody;

function Start()
{
	rb = GetComponent.<Rigidbody>();
}

function Update()
{
	//Calculate the distance between the object and the player
	var dist = Vector3.Distance(transform.position, player.transform.position);

	if (dist < distance)
	{
		//Calculate the vector between the object and the player
		var dir : Vector3 = transform.position - player.transform.position;
		//Cancel out the vertical difference
		dir.y = 0;
		//Translate the object in the direction of the vector
		rb.AddForce(dir.normalized * pushStrength);
	}
}

You should attach one of these scripts to the object to be pushed. Remember to edit the values in the inspector.

Hope this helps!