Home > Mobile >  Ruby: how to calculate distance between two points in a 2d plane?
Ruby: how to calculate distance between two points in a 2d plane?

Time:09-16

I am making some tests of developing simple games using Ruby. I have strong need of playing with 2D Vectors. For example how to easily calculate the distance between 2 points in 2D coordinates system?

I know I can just calculate the hypotenuse of the coordinates substraction but I am wondering if there is any out-of-the-box library or method to do this.

I found Math.distance but it is not working for me (undefined method 'distance' for Math:Module (NoMethodError)) even with require "facets"

CodePudding user response:

Google was not very helpful and it took me a while to find the proper way to do this, so I put here my own answer for future searchers:

For example:

v1 = Vector[1, 1]
v2 = Vector[2, 2]
distance = (v1 - v2).magnitude
=> 1.4142135623730951
  • Related