You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ruby 中如何计算二维平面上两个点之间的距离?

Ruby 2D向量计算及Math.distance报错解决方案

1. 修复Math.distance调用报错问题

facets库默认不会全量加载所有扩展方法,Math.distance属于独立扩展模块,需要单独引入对应文件才能使用:

# 错误引入方式(仅加载核心扩展)
# require "facets"

# 正确引入方式
require "facets/math/distance"

# 调用示例:计算点(1,2)与(4,6)的距离
puts Math.distance(1, 2, 4, 6) # 输出 5.0

2. 游戏开发场景下的2D向量处理方案

如果有大量2D向量运算需求,推荐以下两种方案:

  • 零依赖标准库实现
    直接使用Ruby内置的Math.hypot方法封装距离计算,不需要引入任何第三方库:
    def get_2d_point_distance(x1, y1, x2, y2)
      dx = x2 - x1
      dy = y2 - y1
      Math.hypot(dx, dy)
    end
    
    # 调用示例
    puts get_2d_point_distance(1, 2, 4, 6) # 输出 5.0
    
  • 专用向量库实现
    使用专门的vector2d gem,覆盖游戏开发常用的所有2D向量操作(距离计算、加减、缩放、旋转、归一化、点积叉积等),安装和使用方式如下:
    安装命令:gem install vector2d
    示例代码:
    require "vector2d"
    
    point_a = Vector2d(1, 2)
    point_b = Vector2d(4, 6)
    
    # 计算两点距离
    puts point_a.distance(point_b) # 输出 5.0
    
    # 其他常用操作示例
    puts point_a + point_b # 向量相加,输出 (5, 8)
    puts point_a * 3 # 向量缩放,输出 (3, 6)
    puts point_a.length # 获取向量长度,输出约2.236
    puts point_a.normalize # 向量归一化,输出单位向量
    

内容的提问来源于stack exchange,提问作者fguillen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 00:45:04