プログラミング超初心者のゲーム製作 by Pyxel(7日目)

今日は「動きに変化をだす」を学びます。

今日書いたコード

結果:ニコちゃんが画面左から右に移動し、真ん中まできたら画面上に移動する。加速を追加。

import pyxel

def draw_stuff(x, y, color_a, color_b):
    pyxel.circ(x, y, 5, color_a)
    pyxel.line(x - 2, y - 2, x - 2, y - 1, color_b)
    pyxel.line(x + 2, y - 2, x + 2, y - 1, color_b)
    pyxel.line(x - 2, y + 2, x + 2, y + 2, color_b)

pyxel.init(120, 120, title = "Day07")
stuff_x = 0
stuff_y = 60
stuff_v= 0 #速度

while True:
    if stuff_x < 60:
        pyxel.cls(1)
        draw_stuff(stuff_x, stuff_y, 7, 8 )
        pyxel.flip()
        stuff_x += stuff_v
        stuff_v += 0.05
    elif not stuff_x < 60:
        pyxel.cls(1)
        draw_stuff(stuff_x, stuff_y, 7, 8)
        pyxel.flip()
        stuff_y -= stuff_v
        stuff_v += 0.1

結果:ニコちゃんが小さく跳ねながら右に移動

import pyxel

def draw_stuff(x, y, color_a, color_b):
    pyxel.circ(x, y, 5, color_a)
    pyxel.line(x - 2, y - 2, x - 2, y - 1, color_b)
    pyxel.line(x + 2, y - 2, x + 2, y - 1, color_b)
    pyxel.line(x - 2, y + 2, x + 2, y + 2, color_b)

pyxel.init(120, 120, title = "Day07")

stuff_x = 0 #ニコちゃんのX座標
stuff_y = 30 #ニコちゃんのY座標
stuff_vy = 0 #ニコちゃんのY方向速度
stuff_height = 10
stuff_vx = 0 #ニコちゃんのX方向速度

while True:
    stuff_x += stuff_vx
    stuff_vx +=0.01
    stuff_y += stuff_vy
    stuff_vy += 0.1

    stuff_bounce_y = pyxel.height // 2 - stuff_height
    if stuff_y >= stuff_bounce_y:
        stuff_y = stuff_bounce_y
        stuff_vy *= -0.95

    pyxel.cls(1)
    draw_stuff(stuff_x, stuff_y, 3, 4)
    pyxel.flip()

コードの要点

stuff_vy *= -0.95は、stuff_vyが正の整数値の場合はstuff_yが増え、負の整数値の場合はstuff_yが減る。
これによりバウンドの動きができる。