SLG 后端实战(一):基础建模与行军模拟

SLG 后端实战(一):基础建模与行军模拟

1. 设计说明

1.1 坐标系约定

  • 使用二维笛卡尔坐标系,X 轴向右为正,Y 轴向上为正。
  • 坐标单位为"游戏单位",后续可根据需要缩放(如 1 单位 = 1 米)。

1.2 核心实体

实体 职责 关键属性
Vector2D 二维向量,表示位置或方向 x, y(浮点数)
Army 部队,包含当前位置、目标位置和速度 cur_pos, target_pos, speed
Path(隐式) 由起点和终点定义的直线路径 未显式建模,通过 cur_pos → target_pos 表示

1.3 行军逻辑

  • 部队沿直线从 cur_pos 向 target_pos 匀速移动。

  • 每帧调用 update(dt),dt 为时间增量(秒)。

  • 移动公式:

    复制代码
    \[\text{new\_pos} = \text{cur\_pos} + \frac{\text{target\_pos} - \text{cur\_pos}}{\|\text{target\_pos} - \text{cur\_pos}\|} \times (\text{speed} \times dt)\]

    其中分母为两点间的欧几里得距离,用于归一化方向向量。

1.4 Tick 循环

  • 固定时间步长 TICK_RATE = 0.1 秒(100ms)。
  • 每次 Tick 调用所有部队的 update 方法,更新其位置。

2. 代码实现

2.1 vector2D.py -- 二维向量类

python

python 复制代码
from typing import override

class Vector2D:
    def __init__(self: Vector2D, x: float, y: float):
        self.x = x
        self.y = y

    def __add__(self: Vector2D, other: Vector2D) -> "Vector2D":
        return Vector2D(self.x + other.x, self.y + other.y)

    def __sub__(self: Vector2D, other: Vector2D) -> "Vector2D":
        return Vector2D(self.x - other.x, self.y - other.y)

    def __mul__(self: Vector2D, scalar: float) -> "Vector2D":
        return Vector2D(self.x * scalar, self.y * scalar)

    @override
    def __repr__(self: Vector2D) -> str:
        return f"({self.x:.2f}, {self.y:.2f})"

说明:

  • 支持加、减、标量乘法。
  • __repr__ 格式化为两位小数,便于观察。
  • @override 装饰器并非 Python 内置,此处仅为标记,实际运行时可删除。

2.2 army.py -- 部队类

python

python 复制代码
from vector2D import Vector2D

class Army:
    def __init__(self: "Army", cur_pos: Vector2D, target_pos: Vector2D, speed: float):
        self.cur_pos = cur_pos
        self.target_pos = target_pos
        self.speed = speed

    def __repr__(self: "Army") -> str:
        return f"Army(pos={self.cur_pos}, target={self.target_pos}, speed={self.speed})"

    def update(self: "Army", dt: float) -> None:
        """根据时间增量 dt 移动部队"""
        direction = self.target_pos - self.cur_pos
        distance = (direction.x ** 2 + direction.y ** 2) ** 0.5
        if distance == 0:
            return  # 已到达目标点

        step = dt * self.speed
        if step >= distance:
            self.cur_pos = self.target_pos
        else:
            # 归一化方向向量再乘以步长
            self.cur_pos = self.cur_pos + direction * (step / distance)

关键点:

  • 归一化:direction * (step / distance) 保证了每次移动的距离恰好是 step,方向指向目标。
  • 边界处理:如果一步就能到达,直接设置位置为目标点,避免过冲。

2.3 main.py -- 主程序与 Tick 循环

python

python 复制代码
from army import Army
from vector2D import Vector2D

# 创建一支军队:从 (100,100) 前往 (500,500),速度 50 单位/秒
army = Army(cur_pos=Vector2D(100, 100),
            target_pos=Vector2D(500, 500),
            speed=50)

TICK_RATE = 0.1   # 100ms
TOTAL_TICKS = 20  # 模拟 2 秒

if __name__ == "__main__":
    for tick in range(TOTAL_TICKS):
        army.update(TICK_RATE)
        print(f"Tick {tick}: {army}")

3. 运行示例

执行 python main.py 输出如下(部分节选):

纯文本

复制代码
Tick 0: Army(pos=(156.57, 156.57), target=(500.00, 500.00), speed=50)
Tick 1: Army(pos=(213.14, 213.14), target=(500.00, 500.00), speed=50)
Tick 2: Army(pos=(269.70, 269.70), target=(500.00, 500.00), speed=50)
Tick 3: Army(pos=(326.28, 326.28), target=(500.00, 500.00), speed=50)
Tick 4: Army(pos=(382.84, 382.84), target=(500.00, 500.00), speed=50)
Tick 5: Army(pos=(439.42, 439.42), target=(500.00, 500.00), speed=50)
Tick 6: Army(pos=(495.98, 495.98), target=(500.00, 500.00), speed=50)
Tick 7: Army(pos=(500.00, 500.00), target=(500.00, 500.00), speed=50)
Tick 8: Army(pos=(500.00, 500.00), target=(500.00, 500.00), speed=50)
...

分析:

  • 部队在第 7 个 Tick 到达目标点(约 0.7 秒),此后位置保持不变。
  • 每次移动的步长约为 56.57 单位(50 * 0.1 * sqrt(2)),符合预期。

4. 小结

4.1 今日收获

  • 实现了基础的二维向量类和部队行军模拟。
  • 理解了向量归一化的必要性:避免方向向量长度干扰移动距离。
  • 掌握了固定时间步长的 Tick 循环写法。

4.2 遗留知识点(后续补充)

  • 向量归一化详解:为何要除以模长,数学推导与应用场景。
  • 浮点数 vs 定点数:游戏服务器为何倾向于使用定点数(整数)来避免跨平台精度差异。

4.3 下一篇预告

碰撞检测核心------线段相交:我们将为部队添加碰撞检测功能,判断两支部队是否会在行军途中相遇。

相关推荐
Thanks_ks2 小时前
接口限流是怎么实现的:从固定窗口计数讲到滑动窗口日志
redis·python·限流·滑动窗口·漏桶·令牌桶·固定窗口
choicesages3 小时前
跑通不等于跑对:公开评论抓取里三处不报错的坐标问题
爬虫·python·数据清洗·数据质量·去重
鲸渔4 小时前
【AI Agent系列课程33-FastAPI 基础07】自动文档与接口调试:Swagger UI 和 ReDoc 入门
python·ui·fastapi·ai编程
Nor.na5 小时前
dateutil 4.0.0 之前,闰年的第 366 天落回 12 月 30 日
python
aifannihao6 小时前
AI 学习第 27 课:重排救不回没召回的答案,四个静默坑
python·scikit-learn·学习路线·rag·重排序
Wellijohn6 小时前
`s += x` 到底是 O(n) 还是 O(n²)?我把 CPython 的字符串拼接拆开测了一遍
后端·python·性能优化
钱栈up8 小时前
GitHub 热榜上手|anthropics/skills:18.9万星的 Claude 技能库
python·开源·github
钱栈up9 小时前
烧结秤校准改造:一个 0.93 系数差点让整条日报线算错数
爬虫·python·数据分析
IT空门:门主15 小时前
Spring AI 2.1.0 更新了什么:从 2.0 升上来的完整梳理
人工智能·python·spring