Answer the question
In order to leave comments, you need to log in
Prevent object from going beyond unity screen boundaries?
Hello.
Please tell me how to prevent the object from going beyond the screen. Need to restrict motion at 1080 x 1920 resolution (Portrait screen layout).
I will be very grateful to everyone who will help.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ScreenLimite : MonoBehaviour
{
private Vector2 screenBounds;
// Start is called before the first frame update
void Start()
{
screenBounds = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height, Camera.main.transform.position.z));
}
// Update is called once per frame
void LateUpdate()
{
Vector3 viewPos = transform.position;
viewPos.x = Mathf.Clamp(viewPos.x, screenBounds.x, screenBounds.x * -1);
viewPos.y = Mathf.Clamp(viewPos.y, screenBounds.y, screenBounds.y * -1);
transform.position = viewPos;
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question