- Home /
Resolution independent mouseposition
Hello simple question, how do i get the mouseposition independet? I use scripts like:
mouseposition=Input.mousePosition-new Vector3(Screen.width/2,Screen.height/2,0f);
transform.Rotate(0f,mouseposition.x*Time.deltaTime,mouseposition.y*Time.deltaTime,relativeTo:Space.Self);
For a player using 1680*1050 the highest x is 840, but for a player using 800*600 the highest x is 400=> the player is turning slower, how do i fix this?
Answer by ByteSheep · Apr 26, 2014 at 09:51 PM
You will have to convert your code slightly to use normalized screen positions like this:
// return the normalized mouse position (between 0 to 1) relative to the screen
//will be 0 if the mouse is on the very left
//will be 1 if the mouse is on the very right
float mouseRatioX = Input.mousePosition.x / Screen.width;
float mouseRatioY = Input.mousePosition.y / Screen.height;
//now create a new vector3
mousePos = new Vector3(mouseRatioX - 0.5f, mouseRatioY - 0.5f, 0f);
//mousPos.x and mousPos.y are now between -0.5f to 0.5f
//you could normalize these values if you wanted to get values between -1f to 1f instead
//create a simple rotate speed variable
float rotateSpeed = 100f;
//now rotate, the rotation speed should now be resolution independent
transform.Rotate(0f, mousePos.x * Time.deltaTime * rotateSpeed, mousePos.y * Time.deltaTime * rotateSpeed, Space.Self);
Answer by robertbu · Apr 26, 2014 at 09:44 PM
One solution is to use Viewport Coordinates. Viewport coordinates go from 0.0 in the lower left corner of the screen to 1.0 in the upper right of the screen.
Vector3 mousePos = Camera.main.ScreenToViewportPoint(Input.mousePosition);
mousePos -= new Vector3(0.5f, 0.5f, 0.0f) * factor;
You can then use mousePos.x and mousePos.y in your Rotate(); You will need to define and initialzie 'factor'. Given your current code, start with a value of 500 for 'factor'.
Darn it, this always happens :) Guess I should always refresh the page to check if any answers have been posted in the meantime, before posting my answer.
It happens to me too. Your answer is better explained, and underneath it is the same answer.
Your answer
Follow this Question
Related Questions
increase linecast length 0 Answers
Get Project View position in editor 1 Answer
Problems with turret rotation clamp 1 Answer