1

私はpygameを使用してpythonでヘビゲームを作成しています。キャラクターを移動するために、移動する角度の整数を持っています。度に基づいて移動するために x と y の変化を得る方法はありますか? 例:func(90) # [0, 5]またはfunc(0) # [5, 0]

4

3 に答える 3

9
import math

speed = 5
angle = math.radians(90)    # Remember to convert to radians!
change = [speed * math.cos(angle), speed * math.sin(angle)]
于 2010-12-28T23:20:49.980 に答える
5

角度のサインとコサインに移動の合計量を掛けると、X と Y の変化が得られます。

import math
def func(degrees, magnitude):
    return magnitude * math.cos(math.radians(degrees)), magnitude * math.sin(math.radians(degrees))

>>> func(90,5)
(3.0616169978683831e-16, 5.0)
>>> func(0,5)
(5.0, 0.0)
于 2010-12-28T23:20:29.823 に答える
3

ヘビが特定の角度(たとえば、90度または45度)でしか移動できない場合(このようなゲームでは一般的です)、進むことができる方向は4つまたは8つだけです。角度を許可された増分で割って方向インデックスを取得し、それを使用してX/Yオフセットのテーブルにインデックスを付けることができます。これは、三角法を使用するよりもはるかに高速になります。

x, y = 100, 100   # starting position of the snake

direction = angle / 90 % 4   # convert angle to direction

directions = [(0,-1), (1, 0), (0, 1), (-1, 0)]   # up, right, down, left

# convert the direction to x and y offsets for the next move
xoffset, yoffset = directions[direction]

# calculate the next move
x, y = x + xoffset, y + yoffset

さらに良いことに、角度の概念を完全に省き、方向変数を使用するだけです。次に、ヘビを回転させるのは、方向をインクリメントまたはデクリメントするという単純な問題です。

# rotate counter-clockwise
direction = (direction - 1) % 4

# rotate clockwise
direction = (direction + 1) % 4

これは、必要に応じて8方向(45度刻みで移動)に簡単に拡張できます。

于 2010-12-28T23:57:40.847 に答える