# Transforming position in y-axis (going in the middle) in Unity [closed]

I am making a 2d game where an object goes up, down or in the middle with given Input.

But when the object goes to the middle with GoMiddle() it starts glitching and it can't go back up or down

Vector2 Pos;
public bool DownKeyPressed = false;
public bool UpKeyPressed = false;
public bool MiddleKeyPressed = false;

// Use this for initialization
void Start()
{

}

// Update is called once per frame
void Update()
{
Pos = transform.position;

UMDCOntroller();

transform.position = Pos;
print(Pos.y);
}

void GoDown()
{
if (Pos.y >= 1.2f)
{
Pos = Vector2.Lerp(Pos, new Vector2(Pos.x, Pos.y - 1.2f), 0.1f);
}
else
{
DownKeyPressed = false;
}

}

void GoUp()
{
if (Pos.y <= 2.8f)
{
Pos = Vector2.Lerp(Pos, new Vector2(Pos.x, Pos.y + 1.2f), 0.1f);
}
else
{
UpKeyPressed = false;
}

}

void GoMiddle()
{

if(Pos.y < 2)
{
Pos = Vector2.Lerp(Pos, new Vector2(Pos.x, Pos.y + 1.2f), 0.1f);

}

else if(Pos.y >= 2) {

Pos = Vector2.Lerp(Pos, new Vector2(Pos.x, Pos.y - 1.2f), 0.1f);

}
else
{

MiddleKeyPressed = false;
}

}

void UMDCOntroller()
{

if (Input.GetKeyDown(KeyCode.S))
{
DownKeyPressed = true;

}

if (DownKeyPressed)
{
GoDown();
UpKeyPressed = false;

}

if (Input.GetKeyDown(KeyCode.D))
{

MiddleKeyPressed = true;
}

if(MiddleKeyPressed)
{

GoMiddle();

}

if (Input.GetKeyDown(KeyCode.W))
{

UpKeyPressed = true;

}

if (UpKeyPressed)
{

GoUp();

}

}


Thanks

• add screenshots what are you trying to do. your terms are a bit confusing. Jul 17, 2016 at 8:03
• So basically the game object goes up on the vertical axis (say 20 pixels) when pressed 'W' and goes down on the vertical axis(say 20 pixels). when pressed 'S'. When pressed D it should go back to the middle (or the original starting point). It does reach the middle. However, it jitters (glitch out basically) when it reaches the middle. I hope this clarifies the question.
– kp21
Jul 17, 2016 at 8:42

The problem is that you are moving the object too much up and down every time you check if it is already on the right spot. Therefore it jumps up and down because

if(Pos.y < 2)
Pos = Vector2.Lerp(Pos, new Vector2(Pos.x, Pos.y + 1.2f), 0.1f);


moves it up so far that

else if(Pos.y >= 2)
Pos = Vector2.Lerp(Pos, new Vector2(Pos.x, Pos.y - 1.2f), 0.1f);


kicks in and moves it down again. This never stops, so the object jumps between two positions.

What you have to do is check whether or not the object is in a region near the target and then you stop the movement. This could look like that:

void GoMiddle()
{
float epsilon = 0.1f;
if ((Pos.y >= 2 - epsilon && Pos.y <= 2) || (Pos.y <= 2 + epsilon && Pos.y >= 2))
{
Pos.y = 2;
MiddleKeyPressed = false;
}
else if (Pos.y >= 2)
Pos = Vector2.Lerp(Pos, new Vector2(Pos.x, Pos.y - 1.2f), epsilon);
else if (Pos.y < 2)
Pos = Vector2.Lerp(Pos, new Vector2(Pos.x, Pos.y + 1.2f), epsilon);
}