#python #pygame #2d #sprite
#python #pygame #2d #спрайт
Вопрос:
В настоящее время я пишу программу для своей первой игры на Python (простой шутер сверху вниз), и я до сих пор добирался сюда, используя учебные пособия и примеры онлайн, которые помогут мне создать код.
Мой персонаж может вращаться с помощью векторов, и все это работает так, как я хочу.
Однако, похоже, я не могу заставить игрока двигаться с помощью клавиш со стрелками. Я преобразовал скорость в вектор, и при запуске кода и использовании клавиш со стрелками координаты игроков фактически меняются, и поэтому в моей голове игрок должен двигаться, но это не так.
Мои первоначальные мысли заключаются в том, что player не перерисовывается на поверхность каждый раз и, следовательно, остается в том же положении, но я не уверен, правильно ли это.
Какие поправки / изменения я могу внести, чтобы заставить это работать, поскольку эта проблема сводила меня с ума последние несколько дней.
import math
from random import randint
import pygame
from pygame.math import Vector2
pygame.init()
screen = pygame.display.set_mode((600, 600))
screen_width = 600
screen_height = 600
black = (0, 0, 0)
pygame.display.set_caption("gang")
clock = pygame.time.Clock()
class Character:
def __init__(self, x, y, width, height):
self.x = x
self.y = y
self.width = width
self.height = height
class Player(pygame.sprite.Sprite):
def __init__(self, pos):
super().__init__()
self.image = pygame.Surface((50, 30), pygame.SRCALPHA)
pygame.draw.polygon(self.image, pygame.Color('steelblue2'),
[(0, 0), (50, 15), (0, 30)])
self.orig_image = self.image
self.rect = self.image.get_rect(center=pos)
self.pos = Vector2(pos)
self.velocityx = Vector2(12, 0)
self.velocityy = Vector2(0, 12)
def update(self):
self.rotate()
def rotate(self):
direction = pygame.mouse.get_pos() - self.pos
radius, angle = direction.as_polar()
self.image = pygame.transform.rotate(self.orig_image, -angle)
self.rect = self.image.get_rect(center=self.rect.center)
class Enemy(Character):
def __init__(self, x, y, width, height):
Character.__init__(self, x, y, width, height)
def draw(self, win):
pygame.draw.rect(win, (0, 255, 0), (jeff.x, jeff.y, jeff.width, jeff.height))
def draw_window():
screen.fill((30, 30, 30))
jeff.draw(screen)
all_sprites.update()
all_sprites.draw(screen)
pygame.display.update()
def xor(a, b):
if bool(a) != bool(b):
return True
else:
return False
def game_end():
pygame.font.init()
text = pygame.font.Font('freesansbold.ttf', 32)
text_surface = text.render('Game Over', False, (0, 0, 0))
text_rect = text_surface.get_rect()
text_rect.center = (86, 86)
screen.blit(text_surface, (172, 172))
pygame.display.update()
mag = Player((150, 150))
playersprite = pygame.sprite.RenderPlain(mag)
all_sprites = pygame.sprite.Group(Player((300, 220)))
jeff = Enemy(randint(300, 500), randint(300, 500), 60, 60)
bullets = []
def main():
run = True
while run:
clock.tick(60)
keys = pygame.key.get_pressed()
if xor(keys[pygame.K_a], keys[pygame.K_LEFT]):
mag.pos -= mag.velocityx
print(mag.pos)
elif xor(keys[pygame.K_d], keys[pygame.K_RIGHT]):
mag.pos = mag.velocityx
print(mag.pos)
elif xor(keys[pygame.K_w], keys[pygame.K_UP]):
mag.pos -= mag.velocityy
print(mag.pos)
elif xor(keys[pygame.K_s], keys[pygame.K_DOWN]):
mag.pos = mag.velocityy
print(mag.pos)
draw_window()
main()
Ответ №1:
В вашем коде есть 2 проблемы.
Player
Объект mag
вообще не отображается, потому что вы создали 2-й Player
объект:
mag = Player((150, 150)) playersprite = pygame.sprite.RenderPlain(mag) all_sprites = pygame.sprite.Group(Player((300, 220)))
Создайте 1 Player
объект и добавьте его в pygame.sprite.Group
all_sprites
:
mag = Player((150, 150))
playersprite = pygame.sprite.RenderPlain(mag)
all_sprites = pygame.sprite.Group(mag)
Когда pygame.sprite.Sprite
из .sprite.Group
a отрисовываются с помощью draw()
, то .image
отрисовывается в местоположении, которое определено с помощью .rect
.
Вы должны обновить положение .rect
атрибута с помощью .pos
в .update
:
class Player(pygame.sprite.Sprite):
# [...]
def update(self):
# update position
self.rect.center = (int(self.pos.x), int(self.pos.y))
# update orientation
self.rotate()
def rotate(self):
direction = pygame.mouse.get_pos() - self.pos
radius, angle = direction.as_polar()
self.image = pygame.transform.rotate(self.orig_image, -angle)
self.rect = self.image.get_rect(center=self.rect.center)
Комментарии:
1. Ах! Я понимаю, не уверен, почему я создал там отдельный объект. Большое вам спасибо, все работает хорошо 🙂