Quick Links: Download Gideros Studio | Gideros Documentation | Gideros Development Center | Gideros community chat
Clamping & Remapping the value - Gideros Forum

Clamping & Remapping the value

rrraptorrrraptor Member
edited February 27 in Code snippets
Just want to share two very useful functions.
-- Limits the value to the specified range.
-- v - value to limit
-- min, max - range
function clamp(v, min, max)
	return (v <> min) >< max
end
 
-- Transforms one range to another.
-- v - value to map
-- minSrc - lower bound of the value's current range
-- maxSrc - upper bound of the value's current range
-- minDst - lower bound of the value's target range
-- maxDst - upper bound of the value's target range
-- clampValue - constrain the value to the newly mapped range
function map(v, minSrc, maxSrc, minDst, maxDst, clampValue)
	local newV = (v - minSrc) / (maxSrc - minSrc) * (maxDst - minDst) + minDst
	return not clampValue and newV or clamp(newV, minDst >< maxDst, minDst <> maxDst)
end
As an example:
clamp(20, 0, 100) -> 20
clamp(-20, 0, 100) -> 0
clamp(120, 0, 100) -> 100
map(0.5, 0, 1, 0, 200) -> 100
map(10, 0, 10, 0, 200) -> 200
map(0, -1, 1, 0, 1) -> 0.5

local px1 = Pixel.new(0xff0000, 1, 32, 32)
px1:setAnchorPoint(.5, .5)
stage:addChild(px1)
local px2 = Pixel.new(0x00ff00, 1, 32, 32)
px2:setAnchorPoint(.5, .5)
stage:addChild(px2)
 
function updatePosition(e)
	local minX, minY, maxX, maxY = application:getLogicalBounds()
	local x1 = map(e.x, minX, maxX, minX + 25, maxX - 25)
	px1:setPosition(x1, 25)
 
	local x2 = map(e.x, minX, maxX, 0, maxX / 2, true)
	px2:setPosition(x2, 75)
end
 
stage:addEventListener("mouseMove", updatePosition)
stage:addEventListener("mouseHover", updatePosition)
Tagged:
+1 -1 (+5 / -0 ) Share on Facebook
Sign In or Register to comment.