Invert and convert slider value

时光总嘲笑我的痴心妄想 提交于 2019-12-21 06:36:37

问题


I currently have a vertical slider that is controlled by the user using startDrag. The puck is restricted in movement by a track movieclip that is 115px high.

private function init():void
{
    puck.y = (track.height-puck.height)/2;
    puck.buttonMode = true;
    puck.addEventListener(MouseEvent.MOUSE_DOWN,onMouseDown);
}
private function sendNewValue():void
{
    trace(Math.round(puck.y-track.y+(puck.height/2)));
    var newVal:Number = ; //need some math magic here
    dispatchEvent(new ToolEvent(ToolEvent.SCALE,1));
}
private function onMouseDown(evt:MouseEvent):void
{
    this.stage.addEventListener(MouseEvent.MOUSE_UP,onMouseUp);
    puck.startDrag(false,new Rectangle((track.x + (track.width/2))-(puck.width/2),track.y-(puck.height/2),0,track.height));
}
private function onMouseUp(evt:MouseEvent):void
{
    puck.stopDrag();
    sendNewValue();
}

I can get a value from it using Math.round(puck.y-track.y+(puck.height/2)), which gives me values between 1 and 115 based on the position of the puck.

Now sadly maths is not my strong point at all (helpful for a programmer!), so would someone please explain how I can convert these values so that:

1 = 2
115 = 0
midpoint (115/2) = 1

Edit: kind of like the question here: How do I reverse my sound volume math for my volume slider?, but as well as inverting the value I need to adjust it on a scale.


回答1:


if you're looking for a linear function such that:

f(1)=2 and f(115) = 0

F(x) = 115/67 -x/67 will work

Generalization:

If you looking for a linear function f(x) = a.x + b such that:

f(x1)=y1
f(x2)=y2

then the solution is:

a=(y1-y2)/(x1-x2)
b=y1 - x1*(y1-y2)/(x1-x2)



回答2:


var sliderValue:Number = Math.round(puck.y-track.y+(puck.height/2));
var sliderPercent:Number = (sliderValue / 115);
var result = Math.abs((sliderPercent * 2) - 2);

Let me know if that works. I don't particularly understand the function above so that one might be better. In my code, 55 would give you 1.04 because its more than halfway to the full amount, which is in your case 0 instead of 2 being the full amount.



来源:https://stackoverflow.com/questions/6496205/invert-and-convert-slider-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!