Easy onTouch movement 2D
Hi all, this is my first time posting. English is not my native language so I apologize for any incorrect words or grammar.
I'm new in Unity and game developing in general and I'm trying to create my own 2D game for Android. I want my character to move in the x and y axis but not diagonal movement, just x or y depending on where is the player touching. I have checked a lot of tutorials and posts about what I want to do but I haven't been able to find an answer that fits my requirements, so I have tried to make it myself and have come with something that seems to work for now.
What I have done is write 2 imaginary diagonals on the screen that go from one edge to the oposite one. Then I calculate a few things to get the position of the onTouch.position compared to the 2 diagonals. If the touch was on top of both diagonals, then the player must walk up, if the touch was on top of one and below the other one, it has to move to one of the sides depending on the values, and if touch point was below both diagonals, then player has to move down.
This is the code to do it:
Vector2 move = Vector2.zero;
if (Input.touchCount > 0) {
Touch myTouch = Input.GetTouch(0); // Capture the first touch of the count
Vector2 touchEnd = myTouch.position; // Capture the touch position of the captured touch
float x = touchEnd.x;
float y = touchEnd.y;
float m1 = (float)Screen.height / (float)Screen.width; // diagonal 1 gradient
float m2 = ((float)Screen.height * (-1)) / (float)Screen.width; // diagonal 2 gradient
//diagonal 1
float y1 = m1 * x; // y position of point x of diagonal 1
bool pos_d1 = y > y1 ? true : false; // if true, touch was on top of diagonal 1
//diagonal2
float y2 = (m2 * x) + (float)Screen.height; // y position of point x of diagonal 2
bool pos_d2 = y > y2 ? true : false; // if true, touch was on top of diagonal 2
if (pos_d1 && pos_d2) move.y = -1; // touch is up
else if (pos_d1 && !pos_d2) move.x = -1; // touch is left
else if (!pos_d1 && pos_d2) move.x = 1; // touch is right
else if (!pos_d1 && !pos_d2) move.y = 1; // touch is down
}
And then I use : targetVelocity = move * maxSpeed;
to assign the movement.
At this point, what I want to ask is: Is there an easier way to do this? I feel it may be better ways to deal with this, but I can't seem to find them.
Thank you in advance!
Your answer
![](https://koobas.hobune.stream/wayback/20220612154044im_/https://answers.unity.com/themes/thub/images/avi.jpg)