Reputation: 81
I'm creating a 2D platformer type shooting game using python and pygame, and I'm trying to add in tiling mechanics so If I created a platform 100 pixels long and the tile image was only 70 pixels long, it would draw one tile and half of another, so I created a simple prototype, but I can't get it to draw the sprite. Here's my code for it:
import pygame
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
class Rec(pygame.sprite.Sprite):
def __init__(self, x, y, w, height):
super().__init__()
self.b = 0
self.image = pygame.image.load("grass.png").convert()
if w <= 70:
self.image = pygame.transform.scale(self.image, (w, height))
elif w > 70:
self.image = pygame.Surface([w, height])
while self.b < w:
self.image.blit(pygame.image.load("grass.png").convert(), (x + self.b, y))
self.b += 70
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
pygame.init()
size = (700, 500)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("My Game")
all_sprites_list = pygame.sprite.Group()
rec = Rec(100, 200, 140, 70)
all_sprites_list.add(rec)
done = False
clock = pygame.time.Clock()
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
screen.fill(WHITE)
all_sprites_list.draw(screen)
pygame.display.flip()
clock.tick(60)
pygame.quit()
Upvotes: 1
Views: 1592
Reputation: 101052
The line
self.image.blit(pygame.image.load("grass.png").convert(), (x + self.b, y))
should be
self.image.blit(pygame.image.load("grass.png").convert(), (self.b, 0))
since the position you pass to the blit
function are relative to the Surface
you blit on; but x
and y
are screen coordinates.
So in your example you blit the grass image with a position of x + self.b = 100
, y = 200
on a Surface
which has a size of (140, 70)
, while you should blit the it at (0, 0)
.
Upvotes: 1