- Home /
Question by
Killerpenguin21 · Jul 17, 2016 at 08:38 PM ·
c#unity 2d
Transforming position in y-axis (going in the middle) in Unity
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. I want to fix this. This is my code :-
Vector2 Pos;
public bool DownKeyPressed = false;
public bool UpKeyPressed = false;
public bool MiddleKeyPressed = false;
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();
}
}
Comment
I think you want add in some else statements, eg:
if(key X is pressed)
pressed$$anonymous$$eyX=true;
else
pressed$$anonymous$$eyX=false;
It looks like once you set $$anonymous$$iddle$$anonymous$$eyPressed
to true, you only set it back to false in one special case.
Answer by Killerpenguin21 · Jul 18, 2016 at 06:16 AM
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);
}
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
How to set high score and have it displayed 1 Answer
Unity 5 2D C# interactive grass 2 Answers
cannot implicitly convert type unityengine.vector3' to unityengine.transform' 1 Answer