- Home /
Add force towards input.mouseposition position not working as expected
Hi all, I am at a loss as to how to fix this problem. Seems like i've tried everything. Regardless of what I do when the mouse is clicked force will be added to my player object so that it move to the top right of the screen regardless of where the mouse is positioned.
function FixedUpdate () {
mousePos = Input.mousePosition;
mousePos.z = 0;
mouseDir = mousePos - gameObject.transform.position;
mouseDir = mouseDir.normalized;
if (controlScheme == 0)
{
rigidbody.AddForce((mouseDir) * accelSpeed3D);
}
//Mouse based movement
if (Input.GetMouseButton(0) && PlayerCollision.playerCollisionEvent == false && controlScheme == 0)
{
if (accelSpeed3D <= maxSpeed)
{
accelSpeed3D += accelerationAdd * Time.deltaTime;
}
}
else
{
if (accelSpeed3D >= driftSpeed)
{
accelSpeed3D -= accelerationSubtract * Time.deltaTime;
}
}
}
I know for a fact that the mouse based movement stuff is working properly (as this works with an alternate control scheme), so I'm guessing there is something wrong the direction between the player and the mouse position (mouseDir). Please help!!
Answer by VerrucaG · Mar 03, 2013 at 04:03 PM
I worked this out now. I had to change the Input.mousePosition coordinates to worldspace coordinates using:
mousePos =Camera.main.ScreenToWorldPoint(Input.mousePosition);
instead of
mousePos = Input.mousePosition;
Answer by robertbu · Mar 03, 2013 at 03:57 PM
Mouse position is 2D and in Screen coordinates. Your player is in World coordinates. You have to translate between the two. Note in translating the two coordinates, the Z value is a distance in front of the camera. You are placing the mousePos at 0, so the code below uses distance the camera is away from the origin: (untested):
mousePos = Input.mousePosition;
mousePos.z = Mathf.Abs(0.0 - Camera.main.transform.position.z);
mousePos = Camera.main.ScreenToWorldPoint(mousePos);
Now 'mousePos' is in world coordinates.
Your answer
![](https://koobas.hobune.stream/wayback/20220613093734im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How do I use controller knob input like mouse position? (New Input System) 1 Answer
Movement with AddForce: Wrong Direction 2 Answers
Physics-related touch input (Continuous) 0 Answers
Input.mousePosition only detects motion outside of window if I move really slow. 1 Answer
How do I rotate an object using Vector2 inputs? (New Input System) 1 Answer