Advertisement
ShaunJS

Approach()

Jun 4th, 2016
19,705
0
Never
4
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /// Approach(a, b, amount)
  2. // Moves "a" towards "b" by "amount" and returns the result
  3. // Nice bcause it will not overshoot "b", and works in both directions
  4. // Examples:
  5. //      speed = Approach(speed, max_speed, acceleration);
  6. //      hp = Approach(hp, 0, damage_amount);
  7. //      hp = Approach(hp, max_hp, heal_amount);
  8. //      x = Approach(x, target_x, move_speed);
  9. //      y = Approach(y, target_y, move_speed);
  10.  
  11. if (argument0 < argument1)
  12. {
  13.     argument0 += argument2;
  14.     if (argument0 > argument1)
  15.         return argument1;
  16. }
  17. else
  18. {
  19.     argument0 -= argument2;
  20.     if (argument0 < argument1)
  21.         return argument1;
  22. }
  23. return argument0;
Advertisement
Comments
  • McTakku
    2 years
    # text 0.02 KB | 0 1
    1. doesnt even work
    2.  
  • McTakku
    2 years
    # text 0.05 KB | 0 0
    1. it says it undefined value when trying to run the code
  • McTakku
    2 years
    Comment was deleted
  • le_Liam
    266 days (edited)
    1. here is an updated code for newer GMS2 versions like (v2024.06.2.162)
    2.  
    3. function Approach(_value,_value_to,_amount)
    4. {
    5.  
    6.     if (_value < _value_to)
    7.     {
    8.         _value += _amount;
    9.    
    10.         if (_value > _value_to)
    11.             return _value_to;
    12.  
    13.     }
    14.     else
    15.     {
    16.         _value -= _amount;
    17.         if (_value < _value_to)
    18.             return _value_to;
    19.  
    20.     }
    21.     return _value;
    22. }
    23.  
    24. Keep in mind you can't write the function and expect it to alter a value on its own. You have to write the whole instruction, like this:
    25.  
    26. y = Approach(y, target_y, move_speed);
    27. and not
    28. Approach(y, target_y, move_speed);
    29.  
Add Comment
Please, Sign In to add comment
Advertisement