Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
errors
#1
whenever I press 'W' it crashed without a error
whenever I turn, the tank moves massively
import pygame
import math

window = pygame.display.set_mode((800, 600))
keys = pygame.key.get_pressed()

class Tank:
  def __init__(self):
    self.instance = pygame.image.load('green-tank.png')
    self.rect = self.instance.get_rect(center=(400, 300))
    self.direction = 0
  def frame(self):
    if keys[pygame.K_w] or keys[pygame.K_SPACE]:
      self.rect.x += 3 * sin(self.direction)
      self.rect.y += 3 * cos(self.direction)
    if keys[pygame.K_a] or keys[pygame.K_LEFT]:
      self.direction -= 3
      self.instance = pygame.transform.rotate(self.instance, -3)
    if keys[pygame.K_d] or keys[pygame.K_RIGHT]:
      self.direction += 3
      self.instance = pygame.transform.rotate(self.instance, 3)
    window.blit(self.instance, self.rect)

tank = Tank()

while True:
  for event in pygame.event.get():
    if event.type == pygame.QUIT:
      pygame.quit()
      exit()
  window.fill('black')
      
  keys = pygame.key.get_pressed()
  tank.frame()
  
  pygame.display.flip()
  pygame.time.Clock().tick(120)
Reply
#2
3 radians is a big angle

sin and cos are not defined.

When you rotate an image it gets bigger. Images are rectangles, and the rectangles always align with screen coordinates. When you rotate an image, the corners poke outside of the original bounding rectangle, so the image grows so the entire image fits inside the new rectangle. Unfortunately, the size f the rectangle never shrinks, so it grows bigger and bigger with each rotation. To fix the problem, keep a copy of the original image, and rotate that image to create the image you draw to the screen.
Reply
#3
@deanhystad I'm sorry I added 2 spaces instead of 4 I promise I will get it next time

but the thing is why does it go to the bottom-right corner whenever I rotate it
Reply
#4
I told you why the tank moves when rotated. The image is getting bigger each time it is rotated. To do rotation correctly you need two images. One image is the image you load when the program starts. The second image is the image you blit to the screen. When you want to rotate the image you use the original image to create a new rotated image. Never rotate the rotated image, always rotate the original image.

In you code it would look like this in the __init__():
    self.original_image = pygame.image.load('green-tank.png')
sekf.instance = self.original_image
In the frame() method:
    if keys[pygame.K_a] or keys[pygame.K_LEFT]:
      self.direction -= 3
      self.instance = pygame.transform.rotate(self.original_image, self.direction)
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020