tensaix2j avatar

尝试做一个桌球游戏

tensaix2j

Published: 20 Jun 2020 › Updated: 20 Jun 2020尝试做一个桌球游戏

尝试做一个桌球游戏

image.png

今天来分享制作一个桌球游戏的过程。

自从上个游戏学会用box2d 后,这种物理碰撞游戏就变得非常容易制作。

严格来说这个游戏应该要用 3D 的物理引擎, 因为box2d 只处理2D 的物理。 但有三个部分需要3D 的概念,例如

  1. 洞口对着Z-axis 跟桌面是 orthogonal 的
  2. 球的旋转需要用到X-axis 和 Y-axis rotation 但Box2D 只给Z axis rotation。
  3. box2d 球胡乱打也不会跳出桌子。

如果可以用 3d 物理引擎例如 bullet.js 就很好办,但没办法转去 .ts 。 那就只好用一些workaround 来处理。


简单3个步骤

  1. 建立 Physic Body.

打开blender ,先制作 static body 的polygon 。这个步骤不是在建模而是在制作 Box2d 的 physic body,所以只可以用 Plane Shape。 而且不可以全部在一整块,因为要符合box2d 的Convex Rule。

每一小块都必须是 Convex 的不然collision 不会work。 而且待会把coordinate export 出去,

在 code 里使用时, 建polygon 时必须counter clockwise 的方式建立 array

image.png

2.

建好后, 用 html canvas + js 建 prototype ,因为可以用box2d 的 debugdraw

image.png

一个可以注意的点: 你建Static Body 的polygon 用的vertices array 如果没有用对的顺序(counter clockwise) 放入 coordinate 的话, 你的 polygon 一定是交叉错乱的。

放几颗dynamic circle 进去就可以开打了。 只需要根据棍的角度和距离在白球 ApplyLinearImpulse 就可以实现开球的动作。


3. 用Blender 建模。

这里又回到 Blender , 这次是要建3D 模。

image.png

你可以用刚才在 step 1 的 blend file as 你的 starting point 。 反正就简单的 extrude , edit 一下 mesh 的线条。

只需要做 1/4 个, 然后 mirror on x和 y axis 。完成后 export as GLTF 2.0 。

然后就像上次那样,把 Step2 弄好的 prototype的代码直接copy进 Decentraland SDK 的环境下里的 .ts ,

把那个 桌子的 3D 模型对齐 box2d 的 模型就完成了。

至于那个 洞口, 我是用 一个比较小的 circle 来做 sensor。

还有那个球的 X axis rotation 和 Y axis rotation , 这个很我在youtube 看到有人处理这个问题

X axis rotation 就用 Y 的变化 除以 Circumference周长 在 乘 360。

Y axis rotation 就用 X 的变化 除以 Circumference周长 在 乘 360。

Z axis rotation 基本上就是 box2d dynamic body 提供的。

其实很容易理解的, 球滚了一周长的距离不就是滚了 360 度, 所以你想知道应该rotate 多少度 就是

在那个轴 滚了的距离 / 周长 × 360 度 。

上面 XYZ 轴我是根据 Blender 的, X 就是 左到右, Y 就是前到后, Z就是下到上。我知道在 Unity 或 Decentraland SDK, 你的Y 是下到上的,Z 是前到后, 所以要自己分清楚。

谢谢阅读 。


Leave 尝试做一个桌球游戏 to:

Written by

A Casual Coder / Crypto Trader / Game Developer / 3D Hobbyist

Read more #cn posts


Best Posts From tensaix2j

We have not curated any of tensaix2j's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.

More Posts From tensaix2j