- Home /
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 :D
If you're having trouble thinking about the game, it's like that old game "asteroids".
For collision wall:If you use in your code transform.translate that adds a constant force if you add a collision wall and the player hits it the player will shake but if you have Add velocity your player can have a collision wall.
Answer by Tim-Michels · Jun 25, 2012 at 01:42 PM
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.
Example
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.
Cheers
or $$anonymous$$athf.Clamp(newPos.x, m_$$anonymous$$inX, m_$$anonymous$$axX)
you could also work out m_$$anonymous$$inX and m_$$anonymous$$axX with :
var m_$$anonymous$$inX : float = Camera.main.ScreenToWorldPoint(Vector3(Screen.width*0.05,0.0,0.0)).x;
var m_$$anonymous$$axX : float = Camera.main.ScreenToWorldPoint(Vector3(Screen.width*0.95,0.0,0.0)).x;
same for other axis =]
roncel106 : Yay!! Thanks a lot, about the colliders, how do I position them in the very edge of the screen? :D
Your answer
Follow this Question
Related Questions
A trigger to happen only once. 0 Answers
How to add Circle Collider 2D in script 1 Answer
3D text with box collider Android 1 Answer
Rigidbody not working properly on Android 0 Answers
Tilemap for mobile 1 Answer