Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert arbitrary length to a value between -1.0 a 1.0?

Tags:

math

range

How can I convert a length into a value in the range -1.0 to 1.0?

Example: my stage is 440px in length and accepts mouse events. I would like to click in the middle of the stage, and rather than an output of X = 220, I'd like it to be X = 0. Similarly, I'd like the real X = 0 to become X = -1.0 and the real X = 440 to become X = 1.0.

I don't have access to the stage, so i can't simply center-register it, which would make this process a lot easier. Also, it's not possible to dynamically change the actual size of my stage, so I'm looking for a formula that will translate the mouse's real X coordinate of the stage to evenly fit within a range from -1 to 1.

like image 574
Chunky Chunk Avatar asked Jun 18 '10 03:06

Chunky Chunk


2 Answers

-1 + (2/440)*x

where x is the distance

So, to generalize it, if the minimum normalized value is a and the maximum normalized value is b (in your example a = -1.0, b = 1.0 and the maximum possible value is k (in your example k = 440):

a + x*(b-a)/k

where x is >= 0 and <= k

like image 185
Jacob Avatar answered Sep 22 '22 00:09

Jacob


This is essentially two steps:

  1. Center the range on 0, so for example a range from 400 to 800 moves so it's from -200 to 200. Do this by subtracting the center (average) of the min and max of the range
  2. Divide by the absolute value of the range extremes to convert from a -n to n range to a -1 to 1 range. In the -200 to 200 example, you'd divide by 200
like image 35
Michael Mrozek Avatar answered Sep 21 '22 00:09

Michael Mrozek