- Home /
Stop Pong Paddle from moving offscreen
I'm making a Pong game. I can move the paddle upwards but I can't stop it from disappearing offscreen. How do I make it so that, when it reaches the top of the screen, the paddle will stop. I'm using Java.
This is my code so far:
#pragma strict
//Create a variable to hold player's speed
var speed:int = 10;
function Update ()
{
//Player input
if(Input.GetButton("UP"))
{
transform.Translate(Vector3(0,speed,0) * Time.deltaTime);
}
if(Input.GetButton("Down"))
{
transform.Translate(Vector3(0,-speed,0) * Time.deltaTime);
}
//Check top bounds
if (transform.position.y > 14)
{
transform.position.y = 14;
}
}
It's the part after //Check top bounds that I'm having difficulty with. Thanks in advance.
When you go into scene view while the game is playing, does the paddle stop outside the camera view? Or does it keep going?
Answer by kyrnal · May 28, 2014 at 07:15 PM
Setting manual limits in space is a rock solid way to have it stop. It can be automated to get screen dimensions if need be.
#pragma strict
var speed: float;
var limitUp: float;
var limitDown: float;
private var myTransform: Transform;
private var pos: Vector3;
function Start ()
{
myTransform = gameObject.transform;
}
function Update ()
{
pos = myTransform.position;
if(Input.GetButton("UP"))
{
if(myTransform.position.y >= limitDown)
{
pos.y -= speed;
}
}
if(Input.GetButton("Down"))
{
if(myTransform.position.y <= limitUp)
{
pos.y += speed;
}
}
myTransform.position = pos;
}
Answer by ericdl · May 28, 2014 at 07:04 PM
Your code works. Make sure to set your camera's size property to an appropriate number in the inspector panel. Or, in your code change the transform.position.y
bounds check to something smaller than 14.
Answer by fafase · May 28, 2014 at 07:48 PM
Place two objects in your scene at the position you want the pad to stop an drag them into the slots.
public Transform top;
public Transform bottom;
void Update()
{
float sign = Input.GetAxis("Vertical"));
if(sign == 0) return;
Vector3 pos = transform.position;
pos.y += speed * Time.deltaTime * sign;
pos.y = Mathf.Clamp(pos.y, bottom.position.y, top.position.y);
}
Your answer
Follow this Question
Related Questions
Scoring not working for pong 1 Answer
Scoring not working 2 Answers
Pong AI/Paddle controller help 1 Answer
Simple Collision Deflection (Pong) 1 Answer
Mathf.Clamp isn't stopping movement 1 Answer