Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
102 views
in Technique[技术] by (71.8m points)

python - How to make an image grow in size with pygame


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The image isn't really moving. It might look like its moving towards the bottom-right corner because its getting bigger i.e. its width and height are increasing, which remember, starts at the top left corner of the image. That is where it is drawn as well. So to make it look like its growing, you can offset where its drawn my half the width and the height, which basically means offset it so that it is drawn at the centre. Replace

background.blit(self.image, (self.x_pos, self.y_pos))

with

background.blit(self.image, (self.x_pos - (self.width/2), self.y_pos - (self.height/2)))

Working Example

import pygame

class GrowingImage:

    def __init__(self, image_path, x, y, width, height):
        self.width = width
        self.height = height

        self.object_image = image_path

        self.image = pygame.transform.scale(self.object_image, (self.width, self.height))

        self.x_pos = x
        self.y_pos = y

    def draw(self, background):
        background.blit(self.image, (self.x_pos - (self.width/2), self.y_pos - (self.height/2)))

    def grow(self):
        self.image = pygame.transform.smoothscale(self.object_image, (self.width, self.height))
        self.width += 1
        self.height += 1


pygame.init()

d = pygame.display.set_mode((600, 600))
image = pygame.Surface((1, 1))
growingImage = GrowingImage(image, 300, 300, 20, 20)

while True:
    d.fill((255, 255, 255))
    pygame.event.get()

    growingImage.draw(d)
    growingImage.grow()

    pygame.display.update()
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...