How do I prevent objects from coming out the screen in Android?

Imagine this. I’m creating a simple android game where the player dodges some objects coming towards it. The camera is placed on top (i think it’s called birds eye) and it doesn’t move. I want to play on the field of view of the camera, but the problem is if I move the player on the side, it goes beyond the screen infinitely. How do I prevent this from happening? Please help :smiley:

If you’re having trouble thinking about the game, it’s like that old game “asteroids”.

Depending on how you actually move the character, you should just restrict the movement by code.

When you use physics for your character, you could just place two (invisible) colliders on the sides, preventing the character from passing those “walls”.

If you move the character manually (setting its transform.position), you should have 2 variables (for example m_MinX, m_MaxX).
The code where you move the character should then just clamp its position between the min and max value.


void MoveCharacterToRight()

    Vector3 newPos = transform.position;  //store position
    newPos.x += Time.deltaTime * moveSpeed;  //add movement in x-direction

    if (newPos.x > m_MaxX)
        newPos.x = m_MaxX;  //if x is out of range, set x to maximum x

    transform.position = newPos;  //set its position to clamped position

You can do the opposite for the movement to the left, but the idea remains the same.