0
0

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】2地点を一定の時間で移動する

0
Posted at

はじめに

今作成しているゲームで、2地点を毎回一定の時間で移動したくなったため作成しました。

現在の地点から、クリックした地点を目指して、間を一定の時間で移動します。

import pyxel


class App:
    def __init__(self):
        pyxel.init(160, 120, title="move_constant_time")
        pyxel.mouse(True)
        self.x = 0
        self.y = 0
        self.dx = 0
        self.dy = 0
        self.target_x = 0
        self.target_y = 0
        self.move_frame = 15
        pyxel.run(self.update, self.draw)

    def move_constant_time(self, x, y, dx, dy, target_x, target_y, move_frame):
        """
        一定の時間で移動する
        x, y: 現在の座標
        dx, dy: 移動距離
        target_x, target_y: 目的地の座標
        time: 移動時間
        """
        # ボタンを押したタイミングで移動速度を設定する
        if pyxel.btnp(pyxel.MOUSE_BUTTON_LEFT):
            dx = (target_x - x) / move_frame
            dy = (target_y - y) / move_frame
        
        # 次の座標
        next_x = x + dx
        next_y = y + dy
    
        # Xがターゲットを超えたら止める(クランプ)
        if (dx >= 0 and next_x >= target_x) or (dx <= 0 and next_x <= target_x):
            next_x = target_x
    
        # Yがターゲットを超えたら止める(クランプ)
        if (dy >= 0 and next_y >= target_y) or (dy <= 0 and next_y <= target_y):
            next_y = target_y
    
        x = next_x
        y = next_y
    
        return x, y, dx, dy

    def update(self):

        # クリックした場所を移動座標にセットする
        if pyxel.btnp(pyxel.MOUSE_BUTTON_LEFT):
            self.target_x, self.target_y = pyxel.mouse_x, pyxel.mouse_y

        # 一定の時間で移動
        self.x, self.y, self.dx, self.dy = self.move_constant_time(self.x, self.y, self.dx, self.dy, self.target_x, self.target_y, self.move_frame)

    def draw(self):
        pyxel.cls(0)
        pyxel.circ(self.x, self.y, 3, 6)
        
        pyxel.pset(self.target_x, self.target_y, 10)

App()


pyxel-20260808-231745.gif

動作確認

pyxel code makerで動作確認できるようにしています。
ぜひご確認を↓
pyxel code maker

0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?