Search code examples
javascriptalgorithmequationcreatejs

Coming up with an Algorithm


I have a circle in my canvas. The mouse position is calculated in relation to the canvas. I want the circle to move when the mouse is at <=100px distance from it. The minimum distance to start moving is 100px, at 0.5px/tick. It goes up to 2px/tick at 20px distance.

Basically, the closer the mouse is to the circle, the faster the circle should move.

What I have so far moves the circle when distance is less or equal to 100 -- (I'm using easeljs library)

function handleTick() {
    distance = calculateDistance(circle, mX, mY);
    if (distance<=100) {
        circle.x += 0.3;
    
    stage.update();
    }
}

What I want

function handleTick() {
    distance = calculateDistance(circle, mX, mY);
    if (distance<=100) {
        circleSpeed = // equation that takes distance and outputs velocity px/tick.
        circle.x += circleSpeed;
    
    stage.update();
    }
}

So I thought this was a mathmatical problem and posted it on math exchange, but so far no answers. I tried googling several topics like: "how to come up with an equation for a relation" since I have the domain (100, 20) and the range (0.5, 2). What function can relate them?

Thing is I'm bad at math, and these numbers might not even have a relation - I'm not sure what I'm looking for here.

Should I write a random algorithm "circleSpeed = 2x + 5x;" and hope it does what I want? Or is it possible to do as I did - "I want these to be the minimum and maximum values, now I need to come up with an equation for it"?

A pointer in the right direction would be great because so far I'm shooting in the dark.


Solution

  • If I understand it correctly, you want circleSpeed to be a function of distance, such that

    • circleSpeed is 0.5 when distance is 100.
    • circleSpeed is 2 when distance is 20.

    There are infinity functions which fulfill that, so I will assume linearity.

    The equation of the line with slope m and which contains the point (x₀,y₀) is

    y = m (x-x₀) + y₀
    

    But in this case you have two points, (x₁,y₁) and (x₂,y₂), so you can calculate the slope with

        y₂ - y₁
    m = ───────
        x₂ - x₁
    

    So the equation of the line is

        y₂ - y₁
    y = ─────── (x - x₁) + y₁
        x₂ - x₁
    

    With your data,

        0.5 - 2 
    y = ──────── (x - 20) + 2 = -0.01875 x + 2.375
        100 - 20
    

    Therefore,

    circleSpeed = -0.01875 * distance + 2.375