Answer the question
In order to leave comments, you need to log in
How to make an object move in only a few directions?
Good afternoon.
Let's say there is some object, let's call it Player. How to make it move only in 8 directions? In the figure, red lines indicate only those directions in which the Player can move. At the bottom right of the picture, the Player's movement when clicking on point B, bypassing an obstacle (object). Tell me which way to dig? Something similar to:
Vector2 movement_vector = new Vector2 (Input.GetAxisRaw ("Horizontal"), Input.GetAxisRaw ("Vertical"));
Answer the question
In order to leave comments, you need to log in
How is control actually implemented? at the click point we create a vector to move to this point? or keyboard? it's hard to imagine moving in 8 directions on click
there are some ready-made solutions in 2d https://www.assetstore.unity3d.com/en/#!/content/35803
Code from here
public enum Direction {
None, LeftUp, Up, RightUp, Right, RightDown, Down, LeftDown, Left
}
public Direction GetDirection(double x, double y) {
double absX = Math.Abs(x);
double absY = Math.Abs(y);
if (absX < 0.1 && absY < 0.1) {
// close to center
return Direction.None;
}
if (absX > absY) {
// vertical side
double half = absX * 0.4142;
if (x > 0) {
// left side
if (y > half) return Direction.LeftDown;
if (y < -half) return Diretion.LeftUp;
return Direction.Left;
} else {
// right side
if (y > half) return Direction.RightDown;
if (y < -half) return Direction.RightUp;
return Direction.Right;
}
} else {
// horisontal side
double half = absY * 0.4142;
if (y > 0) {
// bottom
if (x > half) return Direction.RightDown;
if (x < -half) return Direction.LeftDown;
return Direction.Down;
} else {
// top
if (x > half) return Direction.RightUp;
if (x < -half) return Direction.LeftUp;
return Direction.Up;
}
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question