- Home /
Simple Boundaries For Movement
So I'm making a game where you basically move side to side dodging obstacles. It is pretty simple, but what I don't know how to do is make it so that you can't move out of the camera's view. Here's my code, it is pretty simple, but I just need to know how to get bounds in there:
#pragma strict
function Update ()
{
if (Input.GetKey (KeyCode.A)) transform.Translate (Vector3(-6,0,0) * Time.deltaTime);
if (Input.GetKey (KeyCode.D)) transform.Translate (Vector3(6,0,0) * Time.deltaTime);
}
If you couldn't tell, it is a javascript code. It only has the code for moving, not bounds, so if anybody knows how to do that, please tell me. Thanks.
Answer by Itzhak_P · Oct 21, 2016 at 07:27 AM
Hi,
You can use the WorldToScreenPoint to calculate it easily
Transform obj;
Camera CalculationCam;
public void CheckBoundries()
{
Vector2 ObjScreenpoint = CalculationCam.WorldToScreenPoint(obj.transform.position);
if (ObjScreenpoint.x < 0 )
{
// obj is too much left
} else if (ObjScreenpoint.x > Screen.width)
{
// obj is too much right
}
if (ObjScreenpoint.y < 0)
{
// obj is too much down
}
else if (ObjScreenpoint.y > Screen.height)
{
// obj is too much Up
}
}
Good Luck SFC
Answer by OusedGames · Oct 19, 2016 at 01:41 AM
You could move the camera with the player
OR
Create a Box Collider at the borders
And make the player collide with them
Hope it works
The game mechanics involve the camera being stationary, so I can't do that. The problem with the colliders is that 1) The colliders may interfere with other colliders and 2) Usually when I make colliders the objects do not stop fully at the colliders, rather they bounce in and out of the collider borders... Are there any other ways?
Your answer
![](https://koobas.hobune.stream/wayback/20220612094920im_/https://answers.unity.com/themes/thub/images/avi.jpg)