BananarmyG567
BananarmyG567

Reputation: 1

How to convert an -1 through 1 input to 0 through 1 in Lua

How do I convert an -1 through 1 input to 0 through 1. I have tried but have been unsuccessful.

Upvotes: 0

Views: 157

Answers (1)

Paul Kulchenko
Paul Kulchenko

Reputation: 26744

In general, if you want to map some interval x1..x2 to y1..y2, you can apply the following logic:

  1. Shift the interval such that the left side of it is at 0: value-x1
  2. Expand/contract the interval: (y2-y1)/(x2-x1) gives you the ratio by which to expand/contract, so you simply multiple by it: (value-x1)*(y2-y1)/(x2-x1)
  3. Shift the interval to the new position, such that the left side is at y1: (value-x1)*(y2-y1)/(x2-x1)+y1.

Substituting all the values from your example (x1..x2 is -1..1 and y1..y2 is 0..1), we get: (value-(-1))*(1-0)/(1-(-1))+0, which is the same as (value+1)/2.

Upvotes: 2

Related Questions