Here is some code that moves a rocketship sprite left and right. at the end is code that I thought would help it not go out of the window, however, it doesn't work. Does anyone maybe know how to fix the issue?
import pygame
#Set width and height of window
(width, height) = (400, 600)
#sets rocket starting coordinates
rocketX = 200
rocketY = 450
#Sets the colours
background_colour = (0,2,20)
#creates window
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption('Space Dodger')
#All images
#rocket
rocket = pygame.image.load('rocket.png')
rocket = pygame. transform. rotate(rocket, 90)
rocket = pygame.transform.smoothscale(rocket, (50, 100))
screen.fill(background_colour)
running = True
while running:
pygame.display.flip()
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
#makes cursor invisible
pygame.mouse.set_visible(False)
#draws new layer over screen
underlay = pygame.draw.rect(screen, background_colour, (0, 0, 400, 600))
#tracks the mosue location
mouseX, mouseY = pygame.mouse.get_pos()
#displays the rocket
screen.blit(rocket, (rocketX,rocketY))
#sets rocket horizontal position
if mouseX>550:
rocketX=550
else:
rocketX = mouseX
CodePudding user response:
Use a pygame.Rect
object instead of rocketX
and rocketY
:
rocket = pygame.image.load('rocket.png')
rocket = pygame. transform. rotate(rocket, 90)
rocket = pygame.transform.smoothscale(rocket, (50, 100))
rocket_rect = rocket.get_rect(topleft = (200, 450))
Use clamp_ip()
to keep the rectangle in the window:
rocket_rect.clamp_ip(screen.get_rect())
screen.blit(rocket, rocket_rect)
Note, you can get and set the rocket's position using rocket_rect.x
and rocket_rect.y
instead of rocketX
and rocketY
.
CodePudding user response:
Your code is fine, but the threshold you are using is off of the screen. Change 550
to width - 50
(in this case 300):
if mouseX > width - 50:
rocketX = width - 50
else:
rocketX = mouseX