Creating a cube that drops to the bottom of the screen without falling off

I’m learning Unity and I want to set small goals for myself and learn by doing instead of only doing tutorials. My first goal is to create a cube game object, apply physics to it, and have it drop to to the bottom of the screen. I want the bottom of the screen to be the boundary.

        viewPos.x = Mathf.Clamp(viewPos.x, -screenBounds.x + objectWidth, screenBounds.x - objectWidth);
        viewPos.y = Mathf.Clamp(viewPos.y, -screenBounds.y + objectHeight, screenBounds.y - objectHeight);
        viewPos.z = Mathf.Clamp(viewPos.z, mainCamera.nearClipPlane + objectDepth, mainCamera.farClipPlane - objectDepth);

I have created a 3D project and my cube object. I added a RigidBody component to it. I added a script called ConfineToScreen and it does indeed stop the cube in the bottom-ish area. But it goes below the bottom of the viewport. I want the viewport bottom to be the absolute lowest the object will drop.

I’m using Perspective projection. I know my problem is with the Y axis, because I can arbitrarily hardcode it to what I want, but I want to inherit the property from the viewport.

Can anyone see what I’m doing wrong with that y axis?

Can you try this, it will work perfectly for you

using UnityEngine;

public class ConfineToScreen : MonoBehaviour
{
private Camera mainCamera;

void Start()
{
    mainCamera = Camera.main;
}

void Update()
{
    Vector3 viewPos = transform.position;
    float objectHeight = transform.localScale.y / 2;

    // Get the world position at the bottom of the viewport
    float bottomY = mainCamera.ViewportToWorldPoint(new Vector3(0, 0, viewPos.z - mainCamera.transform.position.z)).y;

    // Clamp the y position
    viewPos.y = Mathf.Max(viewPos.y, bottomY + objectHeight);
    transform.position = viewPos;
}

}

I hope this will help you brother….

1 Like

This is excellent! Thanks!