场景物理层的作用

首先需要知道,根据不同的游戏类型、玩法,来决定服务器端场景是否增加物理层。

有场景物理层,则:

  • 服务器可以模拟碰撞以及碰撞后的结果
  • 移动过程全部由服务器计算完成

缺点则是CPU增加物理层代码的运算。

base/ape

本项目使用的物理库为:base/ape

可以直接参考本项目使用代码,了解如何使用base/ape

项目场景物理层构建代码分析 - ScenePhysic.go

  • 碰撞组定义

    type ScenePhysic struct {
      engine    *ape.APEngine
      root      *ape.Group // 固定碰撞群
      blockAll  *ape.Group // 所有MapObject
      animalAll *ape.Group // 所有BallPlayer
      feedGroup *ape.Group // 所有BallFeed
    }
    

    定义了4个碰撞组

    1. root:确定地图边界障碍物
    2. blockAll:所有静态障碍物
    3. animalAll:所有玩家
    4. feedGroup:所有动态障碍物
  • 碰撞组构建

    func (this *ScenePhysic) BuildGroups() {
      this.root = ape.NewGroup(false)
      this.engine.AddGroup(this.root)
    
      this.blockAll = ape.NewGroup(false)
      this.engine.AddGroup(this.blockAll)
    
      this.animalAll = ape.NewGroup(true)
      this.engine.AddGroup(this.animalAll)
    
      this.feedGroup = ape.NewGroup(false)
      this.engine.AddGroup(this.feedGroup)
    
      this.root.AddCollidable(this.animalAll)
      this.blockAll.AddCollidable(this.animalAll)
      this.feedGroup.AddCollidable(this.animalAll)
    }
    

    通过AddCollidable方法调用,让玩家组与其他组会做碰撞检测

  • 构建边界

    func (this *ScenePhysic) CreateBoard(size float32) {
      left := ape.NewRectangleParticle(-size/2, size/2, size, size*2)
      left.SetFixed(true)
      right := ape.NewRectangleParticle(size*3/2, size/2, size, size*2)
      right.SetFixed(true)
      top := ape.NewRectangleParticle(size/2, size*3/2, size*2, size)
      top.SetFixed(true)
      down := ape.NewRectangleParticle(size/2, -size/2, size*2, size)
      down.SetFixed(true)
      fiveColorStone := ape.NewCircleParticle(size, size, 1) //可能引擎问题,右上角会穿透,要堵一下
      fiveColorStone.SetFixed(true)
      this.root.AddParticle(left)
      this.root.AddParticle(right)
      this.root.AddParticle(top)
      this.root.AddParticle(down)
      this.root.AddParticle(fiveColorStone)
    }
    

    就是在地图边界周围放置大块障碍物

  • 如何加入碰撞组,例如:

    func (this *ScenePhysic) AddBlock(block IPartical) {
      this.blockAll.AddParticle(block)
    }
    
  • 物理引擎更新

    func (this *ScenePhysic) Tick() {
      this.engine.Step()
    }
    

以上,base/ape对加入碰撞组的对象,会自动进行碰撞处理等等

关于如何驱动 base/ape库中的物理对象的移动,在<角色制作>中,再做分析

results matching ""

    No results matching ""