gml

A elegant solution to this repetitive code?


I have this code, but it just looks like there should be a way to do it in fewer lines/code.

if (TargetX > Origin[0] + Range) TargetX = Origin[0] + Range;
if (TargetY > Origin[1] + Range) TargetY = Origin[1] + Range;
if (TargetX < Origin[0] - Range) TargetX = Origin[0] - Range;
if (TargetY < Origin[1] - Range) TargetY = Origin[1] - Range;

I'm using a language called GML, but this should be universal as long as the solution doesn't have any really specific built-in functions.


Solution

  • It's not easy to answer your question. For sure, you can dry your code up.

    Observe that you can simplify your call as:

    abs(target - origin) < range
    

    This tells you if, in both directions, your target is in the range origin ± range. Now that you know this, you need to take action if your target is outside range. This can be simplified again: you just need to check if target is greater than origin or viceversa.

    Finally, you should either use arrays for both target and origin, or define a function that you may call. Apparently, range is identical every time.

    You might use a function:

    f(target, origin, range) {
        if (abs(target - origin) > range) {
            target = (target - origin) < 0 ? target-range : target+range
        }
    }
    

    Now it looks like that your code has become longer, but is also more easy to maintain: reduce the risk of writing > instead of <, change the function once to change all checks and so on.