- Home /
How do i keep the object moving while I press a button?
Hey im very new to unity and coding, i know the basics of coding. But im trying to make a game like "Pong" but when i press w which is my up key it moves for a second then stops. here is my player script.
#pragma strict
var speed:int = 10;
function Update ()
{
if(Input.GetButton("UP"))
{
transform.Translate(Vector3(0,speed,0) * Time.deltaTime);
}
if(Input.GetButton("DOWN"))
{
transform.Translate(Vector3(0,-speed,0) * Time.deltaTime);
}
if(transform.position.y > 14)
{
transform.position.y = 14;
}
if(transform.position.y < -12)
{
transform.position.y = -12;
}
}
Answer by Statement · Dec 22, 2013 at 08:19 PM
The code looks fine to me.
Maybe it's the clamp that limits you which cause you a bit of problem? It would behave as if your movement stops after approximately 2.8 seconds (given your speed is 10).
The piece of code that is restricting your movement is this:
if(transform.position.y > 14)
{
transform.position.y = 14;
}
if(transform.position.y < -12)
{
transform.position.y = -12;
}
If you comment that code away for a while, does it work better?
#pragma strict
var speed : int = 10;
function Update () {
if (Input.GetButton("UP"))
transform.Translate(Vector3(0, speed, 0) * Time.deltaTime);
if (Input.GetButton("DOWN"))
transform.Translate(Vector3(0, -speed ,0) * Time.deltaTime);
// if (transform.position.y > 14)
// transform.position.y = 14;
// if (transform.position.y < -12)
// transform.position.y = -12;
}
If the new version of the code allows you to move further, then you need to change the clamping range from [-12, 14] to something larger.
I have no idea what it was but after i restarted unity it worked fine maybe just a glitch idk but thanks any ways :)
Your answer
Follow this Question
Related Questions
Moving an object at different speeds 2 Answers
Placing object in scene 2 Answers
Select Object and move on Right click Position - Error! 0 Answers
Snaping Object to another moving object 0 Answers