How to lock my movement into 16 directions using Mouse (2D isometric)
I want my character to only move 360/16 directions. This means when I input my mouseclick, the character goes along with the closest angle (22.5°s).
I can't find anything about locking this kind of directions.
My click to move code:
public class ClickToMove : MonoBehaviour {
public float speed = 2f;
Vector2 lastClickedPos;
bool moving;
private void Update() {
if (Input.GetMouseButton(0))
{
lastClickedPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
moving = true;
}
if (moving && (Vector2)transform.position != lastClickedPos)
{
float step = speed * Time.deltaTime;
transform.position = Vector2.MoveTowards(transform.position, lastClickedPos, step);
} else
{
moving = false;
}
}
}
Comment
Answer by MagiBen · Feb 19 at 02:06 PM
this is where I am now, however it doesn't work.
public class ClickToMove : MonoBehaviour
{
public float speed = 2f;
Vector2 lastClickedPos;
bool moving;
Vector2 mouseDir;
private void Update() {
var mousePos = Input.mousePosition;
mousePos.x -= Screen.width / 2;
mousePos.y -= Screen.height / 2;
mouseDir = new Vector2(mousePos.x, mousePos.y);
int mouseDirCount = 16;
float angle = Mathf.Atan2(mousePos.y, mousePos.x);
float normalized = Mathf.Repeat(angle / (Mathf.PI * 2f), 1f);
angle = Mathf.Round(normalized * mouseDirCount) * Mathf.PI * 2f / mouseDirCount;
mouseDir = new Vector2(Mathf.Cos(angle), Mathf.Sin(angle));
if (Input.GetMouseButton(0))
{
lastClickedPos = mouseDir;
moving = true;
Debug.Log(mouseDir);
}
if (moving && (Vector2)transform.position != lastClickedPos)
{
float step = speed * Time.deltaTime;
transform.position = Vector2.MoveTowards(transform.position, lastClickedPos, step);
Debug.Log(step);
Debug.Log(lastClickedPos);
Debug.Log(speed);
} else
{
moving = false;
}
}
}
Your answer