A
A
alexandribragimoviz2021-06-21 23:00:01
C++ / C#
alexandribragimoviz, 2021-06-21 23:00:01

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;

    }
}


When I run the test, the object disappears from the screen and rushes from the bottom left corner of the screen to the top right (Or vice versa)

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question