- Home /
How to make a car not go off the screen?
Hi,
I have been having this issue for a long time. I have a car which moves left and right which works fine but the car can go off the screen which I don't want, how can I define the area's in which it can move inside? I have tried lots of other help questions and none of them have helped. I am making this as a 2D game. Here's my car javascript. (gravity is 0)
#pragma strict
var moveLeft : KeyCode;
var moveRight : KeyCode;
var speed : float = 10;
function Update () {
if (Input.GetKey(moveLeft))
{
rigidbody2D.velocity.x = speed;
}
else if (Input.GetKey(moveRight))
{
rigidbody2D.velocity.x = speed * -1;
}
else
{
rigidbody2D.velocity.x = 0;
}
rigidbody2D.velocity.y=0;
}
Thanks in advance -Nathan
Answer by TobiUchiha · Jun 10, 2014 at 06:36 AM
There are 2 things that can be done:
1) Attach a boxcollider to the car and make 2 invisible quads that can act as an invisible wall and attach a boxcollider to them as well.
2)Use Mathf.Clamp to Clamp the position of the car on the x axis.
Answer by Noob_Vulcan · Jun 10, 2014 at 06:13 AM
Attach Box Colliders at the corner Edges . I have a template . Just convert it to your convenience ...
public BoxCollider topWall;
public BoxCollider botWall;
public BoxCollider leftWall;
public BoxCollider rightWall;
// Use this for initialization
void Start ()
{
//localscale is used because of NGUI Camera
topWall.transform.localScale = new Vector3 (Screen.width * 5, 30f, 70f);
topWall.transform.localPosition = new Vector3 (0f, Screen.height / 2f + 15f, 0f); //+15 is done because of the width of collider
botWall.transform.localScale = new Vector3 (Screen.width * 5, 30f, 70f);
botWall.transform.localPosition = new Vector3 (0f, -Screen.height / 2f - 15f, 0f);
rightWall.transform.localScale = new Vector3 (30f, Screen.height * 5, 70f);
rightWall.transform.localPosition = new Vector3 (-Screen.width / 2f - 15f, 0f, 0f);
leftWall.transform.localScale = new Vector3 (30f, Screen.height * 5, 70f);
leftWall.transform.localPosition = new Vector3 (Screen.width / 2f + 15f, 0f, 0f);
}
If your game is portrait Then you might want colliders at the right and left side colliders ..Thats wat m assuming
So what would I attach the code to? And, do I have to make box colliders as well?
no u dont have to make colliders , this code will do it automatically