Skip to content

Instantly share code, notes, and snippets.

@sui77
Created January 30, 2023 22:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sui77/c7b6d3b54654635fb94b35be3ef471dd to your computer and use it in GitHub Desktop.
Save sui77/c7b6d3b54654635fb94b35be3ef471dd to your computer and use it in GitHub Desktop.
Vector2 GetMouseDirection(float distance) {
Vector2 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
float xp = body.position.x;
float yp = body.position.y;
float xm = mousePosition.x;
float ym = mousePosition.y;
float a; float b; float angle;
if (xm >= xp && ym >= yp) {
a=xm-xp;
b=ym-yp;
angle = Mathf.Atan( b / a);
} else if (xm <= xp && ym >= yp) {
a=xp-xm;
b=ym-yp;
angle = Mathf.PI/2 - Mathf.Atan( b / a) + Mathf.PI/2;
} else if (xm <= xp && ym <= yp) {
a=xp-xm;
b=yp-ym;
angle = Mathf.Atan( b / a) + Mathf.PI;
} else {
a=xm-xp;
b=yp-ym;
angle = Mathf.PI/2 - Mathf.Atan( b / a) + (Mathf.PI/2)*3;
}
angle = angle - Mathf.PI/2;
float xr = Mathf.Sin(-angle) * distance;
float yr = Mathf.Cos(-angle) * distance;
Debug.DrawLine (body.position, mousePosition, Color.red, 0.05f, false);
Debug.DrawLine (new Vector2(body.position.x + xr, body.position.y + yr), body.position, Color.green, 0.01f, false);
Debug.DrawLine (new Vector2(body.position.x + xr-0.1f, body.position.y + yr-0.1f), new Vector2(body.position.x + xr+0.1f, body.position.y + yr-0.1f), Color.green, 0.01f, false);
Debug.DrawLine (new Vector2(body.position.x + xr+0.1f, body.position.y + yr-0.1f), new Vector2(body.position.x + xr+0.1f, body.position.y + yr+0.1f), Color.green, 0.01f, false);
Debug.DrawLine (new Vector2(body.position.x + xr+0.1f, body.position.y + yr+0.1f), new Vector2(body.position.x + xr-0.1f, body.position.y + yr+0.1f), Color.green, 0.01f, false);
Debug.DrawLine (new Vector2(body.position.x + xr-0.1f, body.position.y + yr-0.1f), new Vector2(body.position.x + xr-0.1f, body.position.y + yr+0.1f), Color.green, 0.01f, false);
return new Vector2(xr, yr);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment