Envision, Create, Share

Welcome to HBGames, a leading amateur game development forum and Discord server. All are welcome, and amongst our ranks you will find experts in their field from all aspects of video game design and development.

[Resolved] Closest to Value

I've recently encountered an obstacle I somehow can't seem to get past. I want to check which of two values that is closest to a defined value.
So I have two variables, which are dynamic, so I am using this:
Code:
var1 /= 21 ; var2 /= 21 # splits both on 21
# here I want to call a condition to return a boolean true if var1 is closer to 21 than var2, false if not
So basically, the values of var1 and var2 can range within 10 and 50, so if it's as low as 10, the check value would be ~0,47. So in the case, if var1 and var2 has the check values: 0,47 and 1,1 I want the condition to return false, as var2 had the value 1,1 which proves that it was closest to 21 (1,1 is about 23).

There is probably a ridiculously easy way to do this, but I just couldn't find any ways to do it.

I appreciate it! Thanks in advance.
 
Sheol":3e4mwkmq said:
Like this?
Code:
def closerTo21(var1, var2)
	return (21 - var1).abs < (21 - var2).abs
end
Thanks, I just found a method like that, but I had to get which value that was closest to do what I wanted, so I wrote this:
Code:
  def closest(a,b,x)
    ary = [x-a, x-b]
    if ary[0].abs < ary[1].abs
      return a
    elsif ary[1].abs < ary[0].abs
      return b
    else
      return nil
    end
  end
 

Thank you for viewing

HBGames is a leading amateur video game development forum and Discord server open to all ability levels. Feel free to have a nosey around!

Discord

Join our growing and active Discord server to discuss all aspects of game making in a relaxed environment. Join Us

Content

  • Our Games
  • Games in Development
  • Emoji by Twemoji.
    Top