Skip to main content
Added f suffix
Source Link
Stephane Hockenhull
  • 12.1k
  • 1
  • 26
  • 44

Find the normal between the two then scale that normal by the distance wanted.

float distanceWanted = 3.0f;

Vector3 diff = transform.position - player.position;
diff.y = 0;0.0f; // ignore Y (as requested in question)
transform.position = player.position + diff.normalized * distanceWanted;

This will also keep the y of your following object to be exactly the same as player.position, you may want to add a vertical offset relative to the player:

transform.position = new Vector3(0.0f, verticalOffset, 0.0f) + player.position + diff.normalized * distanceWanted;

Find the normal between the two then scale that normal by the distance wanted.

float distanceWanted = 3.0f;

Vector3 diff = transform.position - player.position;
diff.y = 0; // ignore Y
transform.position = player.position + diff.normalized * distanceWanted;

Find the normal between the two then scale that normal by the distance wanted.

float distanceWanted = 3.0f;

Vector3 diff = transform.position - player.position;
diff.y = 0.0f; // ignore Y (as requested in question)
transform.position = player.position + diff.normalized * distanceWanted;

This will also keep the y of your following object to be exactly the same as player.position, you may want to add a vertical offset relative to the player:

transform.position = new Vector3(0.0f, verticalOffset, 0.0f) + player.position + diff.normalized * distanceWanted;
I had the subtraction backward (silly me).
Source Link
Stephane Hockenhull
  • 12.1k
  • 1
  • 26
  • 44

Find the normal between the two then scale that normal by the distance wanted.

float distanceWanted = 3.0f;

Vector3 diff = playertransform.position - transformplayer.position;
diff.y = 0; // ignore Y
transform.position = player.position + diff.normalized * distanceWanted;

Find the normal between the two then scale that normal by the distance wanted.

float distanceWanted = 3.0f;

Vector3 diff = player.position - transform.position;
diff.y = 0; // ignore Y
transform.position = player.position + diff.normalized * distanceWanted;

Find the normal between the two then scale that normal by the distance wanted.

float distanceWanted = 3.0f;

Vector3 diff = transform.position - player.position;
diff.y = 0; // ignore Y
transform.position = player.position + diff.normalized * distanceWanted;
Source Link
Stephane Hockenhull
  • 12.1k
  • 1
  • 26
  • 44

Find the normal between the two then scale that normal by the distance wanted.

float distanceWanted = 3.0f;

Vector3 diff = player.position - transform.position;
diff.y = 0; // ignore Y
transform.position = player.position + diff.normalized * distanceWanted;