Python Pygame精灵没有相应地转向鼠标
我一直在尝试,但基本上我想做一个坦克游戏,它有一个坦克可以通过鼠标转动自己来发射子弹;当你将鼠标转向某个方向时,精灵将准确跟随。问题是,无论发生什么,我都不能用任何代码打开坦克Python Pygame精灵没有相应地转向鼠标,python,pygame,rotation,mouse,Python,Pygame,Rotation,Mouse,我一直在尝试,但基本上我想做一个坦克游戏,它有一个坦克可以通过鼠标转动自己来发射子弹;当你将鼠标转向某个方向时,精灵将准确跟随。问题是,无论发生什么,我都不能用任何代码打开坦克 import os import pygame import math pygame.init() os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (0, 30) icon = pygame.image.load('Sprite3.png') pygam
import os
import pygame
import math
pygame.init()
os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (0, 30)
icon = pygame.image.load('Sprite3.png')
pygame.display.set_icon((icon))
pygame.display.set_caption('DeMass.io')
class Tank(object): # represents the bird, not the game
def __init__(self):
""" The constructor of the class """
self.image = pygame.image.load('Sprite0.png')
# the bird's position
self.x = 0
self.y = 0
def handle_keys(self):
""" Handles Keys """
key = pygame.key.get_pressed()
dist = 1
if key[pygame.K_DOWN] or key[pygame.K_s]:
self.y += dist # move down
elif key[pygame.K_UP] or key[pygame.K_w]:
self.y -= dist # move up
if key[pygame.K_RIGHT] or key[pygame.K_d]:
self.x += dist # move right
elif key[pygame.K_LEFT] or key[pygame.K_a]:
self.x -= dist # move left
def draw(self, surface):
""" Draw on surface """
# blit yourself at your current position
surface.blit(self.image, (self.x, self.y))
w = 1900
h = 10000
screen = pygame.display.set_mode((w, h))
tank = Tank() # create an instance
clock = pygame.time.Clock()
connection_angle = 90
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit() # quit the screen
running = False
screen.fill((255, 255, 255))
tank.draw(screen)
pygame.display.update()
tank.handle_keys()
clock.tick(100)
您可以使用内置的
math
模块中的atan2
函数来计算两个坐标之间的角度,
然后相应地旋转精灵:
import pygame
from math import atan2, degrees
wn = pygame.display.set_mode((400, 400))
class Player(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((30, 40), pygame.SRCALPHA)
self.image.fill((255, 0, 0))
self.rect = self.image.get_rect(topleft=(185, 180))
def point_at(self, x, y):
rotated_image = pygame.transform.rotate(self.image, degrees(atan2(x-self.rect.x, y-self.rect.y)))
new_rect = rotated_image.get_rect(center=self.rect.center)
wn.fill((0, 0, 0))
wn.blit(rotated_image, new_rect.topleft)
player = Player()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
elif event.type == pygame.MOUSEMOTION:
player.point_at(*pygame.mouse.get_pos())
pygame.display.update()
输出:
您的代码中没有关于用鼠标移动坦克的内容。它使用wasd和箭头键您想将坦克移动到鼠标光标处,还是让坦克转向鼠标光标?或者让坦克的炮塔转向面对光标?坦克应该立即转向鼠标光标,还是以一定的速度开始转向该方向?如果我有点不清楚的话,请严格说明你的要求。我想在这段代码中添加一个额外的函数,以便精灵可以用鼠标旋转。谢谢!也可以移动精灵吗?谢谢@你的意思是让它跟着老鼠吗?@BetterNot see@AnnZen嗯,不太好,我希望用“WASD”移动精灵,同时用鼠标转动精灵。我得到了“WASD”部分,但没有鼠标的转动。有可能把这两个功能放在一起吗?PS,是否可以将图像更改为其他内容?谢谢