- Home /
making boundry for sidescroller
hey all, im trying to make a simple script so if my player object hits the top of ther screen he stops moving up and just stays on screen at the top until he is moved down. and visa versa for the bottom. ive tried using collision on a boundry box with no luck so trying out a script, however im not sure how to go about it thanks
btw my movement script so far is this
public class Runner : MonoBehaviour {
void Update () {
transform.Translate(5f * Time.deltaTime, 0f, 0f);
if ( Input.GetKey(KeyCode.UpArrow) )
transform.Translate(5f * Time.deltaTime, 20f * Time.deltaTime, 0f);
if ( Input.GetKey(KeyCode.DownArrow) )
transform.Translate(5f * Time.deltaTime, -20f * Time.deltaTime, 0f);
}
}
Answer by Maui-M · Feb 05, 2014 at 11:35 PM
A simple way to do it would be to clamp the transform.Y value to a min/max height;
int maxHeight = 200f;
itn minHeight = 0f;
public class Runner : MonoBehaviour {
void Update () {
transform.Translate(5f * Time.deltaTime, 0f, 0f);
if ( Input.GetKey(KeyCode.UpArrow) ) {
transform.Translate(5f * Time.deltaTime, 20f * Time.deltaTime, 0f);
transform.y = transform.y > maxHeight ? maxHeight : transform.y; // max height
}
if ( Input.GetKey(KeyCode.DownArrow) ){
transform.Translate(5f * Time.deltaTime, -20f * Time.deltaTime, 0f);
transform.y = transform.y < minHeight ? minHeight : transform.y; //min height
}
}
}
i have sort of got it working, using the script below. however when i hold down the mouse key and the player hits the top limit, it flickers up and down, in a frantic way. im not sure how to make it smoothly stay at the top of the screen when held up.
void Update () {
//time = Time.time;
Debug.Log (Time.time);
transform.Translate(5f * Time.deltaTime, -20f * Time.deltaTime, 0f);
if ( Input.Get$$anonymous$$ouseButton(0) )
transform.Translate(0f, 60f * Time.deltaTime, 0f);
if ( transform.position.y <= -4)
transform.Translate(0f,20f * Time.deltaTime , 0f);
if ( transform.position.y >= 4)
transform.Translate(0f, -60f * Time.deltaTime , 0f);
}
float maxHeight = 4.0f;
float $$anonymous$$Height = -4.0f;
void Update () {
Debug.Log (Time.time);
Vector3 offset = new Vector3(5f * Time.deltaTime, -20f * Time.deltaTime, 0f);
if(Input.Get$$anonymous$$ouseButton(0))
offset.y = 60f * Time.deltaTime;
else
offset.y = -20f * Time.deltaTime;
float newY = transform.position.y + offset.y;
if(newY >= maxHeight)
offset.y = maxHeight - transform.position.y;
if(newY <= $$anonymous$$Height)
offset.y = $$anonymous$$Height - transform.position.y;
transform.Translate(offset.x, offset.y, offset.z);
}
thankyou! that works great on the top of the screen however now the player is bouncing up and down if i dont hold a key and let him fall to the bottom :/
$$anonymous$$y line 17 was off, use:
offset.y = $$anonymous$$Height - transform.position.y;