0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

はじめてのPyxelとPymunkのサンプルプログラム その1

Last updated at Posted at 2025-11-01

pyxelとpymunk、はじめの一歩

2Dゲームエンジンpyxelと2D物理エンジンpymunkを使って、ボールが落下するpythonスクリプトです。

  • 画面200,150
  • 地面とボール
  • ボールが落下する。
  • スペースキーでリセットする。
pyxel_pymunk_ball.py
pyxel_pymunk_ball.py
# pyxel_pymunk_ball.py
# pip install pyxel pymunk

import pyxel
import pymunk

class App:
    def __init__(self):
        pyxel.init(200, 150, title="Pyxel + pymunk: Bouncing Ball")
        self.space = pymunk.Space()
        self.space.gravity = (0, 400)  # y方向の重力

        # 床(静的剛体)
        floor = pymunk.Segment(self.space.static_body, (0, 130), (200, 130), 0)
        floor.elasticity = 0.9  # 反発係数
        self.space.add(floor)

        # ボール(動的剛体)
        mass, radius = 1, 8
        moment = pymunk.moment_for_circle(mass, 0, radius)
        self.ball_body = pymunk.Body(mass, moment)
        self.ball_body.position = (100, 50)
        self.ball_shape = pymunk.Circle(self.ball_body, radius)
        self.ball_shape.elasticity = 0.8
        self.space.add(self.ball_body, self.ball_shape)

        pyxel.run(self.update, self.draw)

    def update(self):
        # スペースキーでボールをリセット
        if pyxel.btnp(pyxel.KEY_SPACE):
            self.ball_body.position = (100, 50)
            self.ball_body.velocity = (0, 0)
        # 物理計算(1/60秒ステップ)
        self.space.step(1/60)

    def draw(self):
        pyxel.cls(0)
        # 床
        pyxel.rect(0, 130, 200, 20, 5)
        # ボール
        x, y = self.ball_body.position
        pyxel.circ(int(x), int(y), 8, 9)
        # テキスト
        pyxel.text(5, 5, "Press SPACE to reset", 7)

App()

pyxel-20251101-095935.gif

GIFアニメーションを作成する

実行後、ノートPCだと、動画キャプチャー(GIFアニメーション)は、Fn + Alt + 3 です。デスクトップにpyxel-20251101-095935.gifで保存されました。

一歩一歩です。ありがとうございます。

PyxelとPymunkのサンプルプログラム その2 (6ファイル)

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?