Created
January 30, 2023 22:38
-
-
Save sui77/c7b6d3b54654635fb94b35be3ef471dd to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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