- Home /
How to restrict the player to not go below or above the screen
Hi
I am new to Unity and programming. I am making a game(in 3D) where there is a player and a camera both moves at a same speed in x axis. and user has only control to move the player up and down to avoid the obstacles which are coming towards him (So player is moving from left to right and obstacles from right to left).
But my problem is I am not able to restrict the player going out of screen. i.e if I keep pressing up arrow player goes out of screen same for down arrow. There are some answers for this in this forum but I am not able to make it work. Here is my code for camera and player
For Camera Controll
function Update () {
transform.position.x += ManControll.moveSpeed * Time.deltaTime;
}
For player control
pragma strict
static var moveSpeed:float = 5; var updownSpeed:float = 100;
function Update () {
transform.position.x += moveSpeed Time.deltaTime; transform.position.y += updownSpeed Input.GetAxis("Vertical") * Time.deltaTime;
}
Answer by brycem24 · Aug 16, 2014 at 08:55 PM
You could always use empty game objects with colliders attached as an invisible barrier.
You don't even need the colliders if you change your update loop with some logic. Here's some pseudocode: 1. Calculate the new y position. 2. Is this y value higher than the y value of our top gameobject? 3. Is this y value lower than the y value of our bottom gameobject? 4. If no to both: change the transform.position.y value to the new one.
Thanks for the answers, It is working now. I have marked answer as accepted
Your answer
![](https://koobas.hobune.stream/wayback/20220613160638im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Screen.width and Screen.height sometimes flipped for Android 1 Answer
Ligning up a health bar. 1 Answer
When are Screen.width and Screen.height updated after changing the Screen.orientation value? 0 Answers
Unity 3.5.7 Android Screen returns the wrong value? 0 Answers
Make area adapt to screen size 1 Answer