How to bound gameobject within screen Unity

C# code to keep player or gameobject within the Screen view

[1] This will bound gameobject within screen unity and keep the pivot point a game object visible:

using UnityEngine;
using System.Collections;
public class Example : MonoBehaviour {

 void Update() {
    Vector3 pos = Camera.main.WorldToViewportPoint (transform.position);
    pos.x = Mathf.Clamp01(pos.x);
    pos.y = Mathf.Clamp01(pos.y);
    transform.position = Camera.main.ViewportToWorldPoint(pos);
 }
}

You can clamp it tighter if needed. Example:

pos.x = Mathf.Clamp(pos.x, 0.1, 0.9);
Viewport coordinates start at (0,0) in the lower left of the screen and go to (1,1) in the upper right. This code forces an object to have a viewport coordinate in the (0,0) to (1,1) range, and therefore to be on the screen.

[2] This will clamp the movement; i.e. it will feel like an invisible wall around the edges of the screen.

Just make sure this code happens after any physics movement adjustments, and you should be able to keep your rigidbody  stuff. If you encounter jitter, consider changing the code to something like this:

Vector3 pos = Camera.main.WorldToViewportPoint (ship.transform.position);
pos.x = Mathf.Clamp01(pos.x);
pos.y = Mathf.Clamp01(pos.y);

Vector3 speed = ship.rb.velocity;
if(pos.x == 0 || pos.x == 1)
    speed.x = 0;
if(pos.y == 0 || pos.y == 1)
    speed.y = 0;

ship.transform.position = Camera.main.ViewportToWorldPoint(pos);
ship.rb.velocity = speed;

Questions:

  • How to keep an object within the camera view?
  • Limiting x and y movement so you can’t go off camera
  • Keeping a rigidbody within the screen bounds?
  • how to make the player stay within screen in a simple 2d game. C#
  • how to limit rigidbody to stay on screen

References:

1. How to keep an object within the camera view? By: Ashky

2. Limiting x and y movement so you can’t go off camera By: Ketura

1 thought on “How to bound gameobject within screen Unity”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: