- Home /
2D Vector Movement,Vectorel Movement with Buttons
Hello guys,
I am making kind of tetris game for android and want my object move one by one. It's actually written for keyboard but i need this as a version of UI button.
the problem must be pretty easy to solve I think, but i am also pretty new.
Here is the thing,
Example For Keyboard:
if (Input.GetKeyDown(KeyCode.LeftArrow))
{
transform.position += new Vector3(-1, 0, 0);
if (IsValidGridPosition())
{
UpdateMatrixGrid();
}
else
{
transform.position += new Vector3(1, 0, 0);
}
}
I have to put this into my "left controller button". When I press that UI button on the screen, the Object must move just like this as vectorel. The time movements are making problem in the game.
Answer by ekshilimone · Jan 01, 2019 at 09:04 PM
i think u are mistaken :/ bec the if part is not working.
void Update ()
{
if (**Input**.GetKeyDown(KeyCode.LeftArrow))
{
MoveLeft();
}
else if (Input.GetKeyDown(KeyCode.RightArrow))
{
MoveRight();
}
}
public void MoveLeft()
{
transform.position += Vector3.left;
}
public void MoveRight()
{
transform.position += Vector3.right;
}
}
i cant use input coding. bec the buttons on the screen and must be able to use in android screen. thanks.
It doesn’t matter. You don’t need the input coding anymore. You can delete it. All you need to do is assign the moveleft and moveright functions to their respective buttons. That’s it. Did you even try that? And why did you post this as an answer?
Answer by sean244 · Jan 01, 2019 at 07:35 PM
Rewrite your code to the following
using UnityEngine;
public class Block : MonoBehaviour
{
void Update ()
{
if (Input.GetKeyDown(KeyCode.LeftArrow))
{
MoveLeft();
}
else if (Input.GetKeyDown(KeyCode.RightArrow))
{
MoveRight();
}
}
public void MoveLeft()
{
transform.position += Vector3.left;
}
public void MoveRight()
{
transform.position += Vector3.right;
}
}
Then have your 'MoveLeft' button call the 'MoveLeft' function, and have your 'MoveRight' button call the 'MoveRight' function.