Pythonはxの変化とyの変化に変換します
-
13-10-2019 - |
質問
私はPygameを使用してPythonでヘビゲームを作成しています。キャラクターを動かすために、整数を持っています。 xとyの変更を取得して、学位に基づいて移動する方法はありますか?例えば: func(90) # [0, 5]
また func(0) # [5, 0]
解決
import math
speed = 5
angle = math.radians(90) # Remember to convert to radians!
change = [speed * math.cos(angle), speed * math.sin(angle)]
他のヒント
角度の正弦とコサインには、移動の総量を掛けて、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)
そのようなゲームで典型的な特定の角度(例: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度の増分で移動)。
所属していません StackOverflow