thelearnerofcode
thelearnerofcode

Reputation: 346

How to move the player to a specific point in a 2D Unity Game

I have something like this in my game:

Vector2 screenPosition = Camera.main.WorldToScreenPoint(transform.position);
if (screenPosition.y > Screen.height || screenPosition.y < 0)
{

}

Which finds if the player is not in the window. I want it to move the player to a specific coordinate. So what would teleport the player to those coordinates?

Upvotes: 0

Views: 987

Answers (1)

Mohanad S. Hamed
Mohanad S. Hamed

Reputation: 301

Try the following code

Vector2 screenPosition = Camera.main.WorldToScreenPoint(transform.position);
float targetX = 100; // replace it with your value
float targetY = 100; // replace it with your value
if (screenPosition.y > Screen.height || screenPosition.y < 0)
{
     transform.position = Camera.main.ScreenToWorldPoint(new Vector3(targetX, targetY, camera.nearClipPlane));
}

Upvotes: 1

Related Questions