- Home /
AddForce to mouse direction not working well horizontally.
I'm making a 2d platformer in which I'd like to have a cube dash in the direction of the mouse when you click. Problem is that the character is dashing upwards way more than when it dashes to the sides (diagonally it dashes more than to the side but less than upwards), it basically fires up when clicking above it and moves a bit when going to the sides. I want the character to stay in place after dashing although it seems that this doesn't affect the dashing. Code:
m_Grounded = false;
var mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
var mouseDir = mousePos - gameObject.transform.position;
mouseDir.z = 0.0f;
mouseDir = mouseDir.normalized;
m_Rigidbody2D.gravityScale = 0;
m_Rigidbody2D.drag = m_Drag;
m_Rigidbody2D.AddForce(mouseDir * m_dashForce);
Answer by Llama_w_2Ls · Jan 20, 2021 at 08:59 AM
You might want to adjust your mouse position by the length and width of the screen, since most mobile devices aren't squares, but elongated rectangles that stretch more, horizontally, than vertically.
You can get the resolution of your screen by using Screen.width
and Screen.height
. Then, you might want to divide mousepos.x by Screen width, same for height, to keep your values relatively similar. @Sylfur