[英]How To draw a changing trajectory with direction and angle as values in Python
我想做的是在玩第一人称射击游戏时收集键盘和鼠标输入数据。 我可以用 SerpentAI 记录这些数据并将其保存到文件中。
然后,当我在游戏中的地图中移动时,我想画出我的轨迹。 所以我的输入是键盘上的“w”、“a”、“s”和“d”键,“w”代表向前移动一个,“s”代表向后移动一个,“a”向左移动一个, 'd' 向右移动一个。
我的问题是我也有鼠标输入可以改变“前进”的方向。 例如:我在游戏中按'w'直线移动,然后将鼠标移动一定距离进行90度转弯,然后再次按'w'。 我仍在前进,但朝着新的方向前进。 这在我的数据中会发生很多次,我不知道如何绘制它。
为了让事情变得更简单,我创建了一个虚拟数据集,其中包含一些应该导致绘制正方形的输入:
键盘 | 鼠标转角 | 时间戳 |
---|---|---|
w | 1657161124 | |
w | 1657161125 | |
w | 1657161126 | |
90 | 1657161127 | |
w | 1657161128 | |
w | 1657161129 | |
w | 1657161130 | |
90 | 1657161131 | |
w | 1657161132 | |
w | 1657161133 | |
w | 1657161134 | |
90 | 1657161135 | |
w | 1657161136 | |
w | 1657161137 | |
w | 1657161138 |
到目前为止,我已经使用 pandas 为每个时间戳创建坐标,然后使用 matplotlib 绘制坐标的散点图,但是我生成的坐标不正确,而且我的 python 几何可视化知识无法完成这项任务。 我没有办法生成正确的坐标。
我一直在尝试使用 shapely 库,特别是 shapely.affinity.rotate 以帮助获得正确的坐标,但到目前为止还没有运气。
由于您的时间戳是等距的,并且您的键盘和鼠标输入是互斥的,您可以将此任务简化为对操作列表的解释:
import numpy as np
from matplotlib import pyplot as plt
actions = ["w", "a", "s", "d", 90, "w", "a", "a", -180, "s", "d", "w", 90, "w", "w", "a", "a", "a"]
delta_times = [1,2,5,3,5,1,1, 2, 3, 2, 2, 1, 1, 1, 4, 2, 1, 1]
# initial direction and position
direction = np.array((0,1)) # moving in +y
position = np.array((0,0))
# change relative direction
movement_translator = {
"w": lambda pos, direction: pos + direction,
"s": lambda pos, direction: pos - direction,
"a": lambda pos, direction: pos - np.flip(direction),
"d": lambda pos, direction: pos + np.flip(direction),
}
# change direction
def rotatation_matrix(deg):
theta = np.deg2rad(deg)
return np.array([[np.cos(theta), -np.sin(theta)], [np.sin(theta), np.cos(theta)]])
# show live movement
def plot_movement(x_pos, y_pos, position, direction):
plt.cla()
plt.plot(x_pos, y_pos, '.-')
plt.plot(x_pos[-1], y_pos[-1], 'xr') # show current position as red x
plt.show(block=False)
plt.title(f"Position: {np.round(position)}, Direction: {np.round(direction)}")
plt.pause(1)
# initialize position lists
x_pos = [position[0]]
y_pos = [position[1]]
for action, delta_time in zip(actions, delta_times):
try: # to apply movement, i.e. w,a,s,d
for _ in range(delta_time):
# keep moving in same direction
position = movement_translator[action](position, direction)
x_pos.append(position[0])
y_pos.append(position[1])
plot_movement(x_pos, y_pos, position, direction)
except KeyError: # it is not a movement, so apply rotation instead
direction = np.dot(rotatation_matrix(action), direction)
for _ in range(delta_time):
plt.pause(1) # just wait
plt.show()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.