Skip to main content
Don't repeat tags in title
Link
DMGregory
  • 141k
  • 23
  • 258
  • 401

Unity: Teleport to random point behind Camera and within boundaries

Source Link

Unity: Teleport to random point behind Camera and within boundaries

I'm creating a third person game with companions following the player. The companions have a mechanic in which if they are too far away from the player and out of camera view, they'll be teleported behind the player.

I've already got the the distance and camera view parts working, but I'm having trouble with the spawn position point.

They companions need to be teleported behind the camera's view and within the boundaries of an area, which includes colliders. Right now, they teleport outside the map and fall out of the world.

I need some way to calculate a safe position to teleport to.

This is all I have so far:

Vector3 randomPosition = Camera.main.ViewportToWorldPoint(new Vector3(0, 1, -4));
transform.position = randomPosition;

Example of an area:

Example of an area with boundaries