python - 如何在pygame中进行平滑移动+旋转?
问题描述
我正在尝试使宇宙飞船向鼠标指针移动,如果它四处移动,则旋转以跟随指针。目前,旋转工作正常,线性运动工作正常,但由于某种原因,如果船同时旋转和移动,它会在旋转时在原地晃动,不再向前移动。这是我的问题的 gif以供澄清。下面我有相关的代码。
编辑:我刚刚发布了整个课程,希望能让事情变得不那么混乱。
class player():
def __init__(self, x_position, y_position, length, height):
self.x = x_position
self.y = y_position
self.l = length
self.h = height
self.player_ship = pygame.transform.scale(ships[0], (128, 128))
self.angle = 0
def draw(self, win):
cx, cy = pygame.mouse.get_pos()
img_copy = pygame.transform.rotate(self.player_ship, math.atan2(self.x - cx, self.y - cy)*57.2957795)
win.blit(img_copy, (self.x - int(img_copy.get_width() / 2), self.y - int(img_copy.get_height() / 2)))
def move(self, speed):
cx, cy = pygame.mouse.get_pos()
self.angle = math.atan2(cx - self.x, cy - self.y)*57.2957795
movement_x = math.cos(self.angle) * speed
movement_y = math.sin(self.angle) * speed
self.x -= movement_x
self.y += movement_y
我在某处读到我不应该将我的位置存储为整数,但我不完全确定如何跟踪位置。我非常感谢任何人提供的任何提示或指示。
解决方案
该问题是由旋转精灵的代码引起的。
旋转图像,得到pygame.Rect
涂层图像。通过对象的位置设置矩形的中心。使用矩形来blit图像。
请参阅如何使用 Pygame 围绕其中心旋转图像?.
img_copy = pygame.transform.rotate(self.player_ship, self.angle)
rotated_rect = img_copy.get_rect(center = (round(self.x), round(self.y)))
要旋转图像,只需计算从当前位置到鼠标位置的单位方向矢量 [参见单位矢量。)]。按速度缩放矢量并将其添加到位置:
cx, cy = pygame.mouse.get_pos()
dx, dy = cx - self.x, cy - self.y
if abs(dx) > 0 or abs(dy) > 0:
dist = math.hypot(dx, dy)
self.x += min(dist, speed) * dx/dist
self.y += min(dist, speed) * dy/dist
看例子
class player():
def __init__(self, x_position, y_position, length, height):
self.x = x_position
self.y = y_position
self.l = length
self.h = height
self.player_ship = pygame.transform.scale(ships[0], (128, 128))
self.angle = 0
def draw(self, win):
cx, cy = pygame.mouse.get_pos()
dx, dy = cx - self.x, cy - self.y
if abs(dx) > 0 or abs(dy) > 0:
self.angle = math.atan2(-dx, -dy)*57.2957795
img_copy = pygame.transform.rotate(self.player_ship, self.angle)
rotated_rect = img_copy.get_rect(center = (round(self.x), round(self.y)))
win.blit(img_copy, rotated_rect)
def move(self, speed):
cx, cy = pygame.mouse.get_pos()
dx, dy = cx - self.x, cy - self.y
if abs(dx) > 0 or abs(dy) > 0:
dist = math.hypot(dx, dy)
self.x += min(dist, speed) * dx/dist
self.y += min(dist, speed) * dy/dist
推荐阅读
- java - Apple Wallet jpasskit 苹果设备在设置 webserviceurl 时无法识别
- google-cloud-platform - GCP 测试版服务的可靠性如何?
- android - ARCore - 在平面上显示 3D 模型
- python - 如何在另一个函数中使用另一个函数中的函数中的变量
- python - Pyhook 等到 keyup
- azure - 使用守护程序/控制台应用程序调用 Azure AD 保护自己的 Web API n 具有特定范围
- tensorflow - 调试 tf.data.Dataset.map
- ember.js - ember 中带有查询参数的链接
- r - 在 gglot2 中使用 SVG 图像作为符号
- elasticsearch - ElasticSearch - 比较两个时间段内的不同值