Pygame 2D tiled game, moving camera. Character moving faster than camera - python

I had a problem with creating camera in pygame, I assumed code below should work but our player is moving faster than camera and is going out of the window. Somebody know what's the issue?
import pygame, sys
class Player(pygame.sprite.Sprite):
def __init__(self, pos, group):
super().__init__(group)
self.image = pygame.image.load('./chatacters/players/player_one.png').convert_alpha()
self.rect = self.image.get_rect(center=(640, 360))
self.direction = pygame.math.Vector2()
self.speed = 5
# key inputs
def input(self):
keys = pygame.key.get_pressed()
if keys[pygame.K_UP]:
self.direction.y = -1
elif keys[pygame.K_DOWN]:
self.direction.y = 1
else:
self.direction.y = 0
if keys[pygame.K_LEFT]:
self.direction.x = -1
elif keys[pygame.K_RIGHT]:
self.direction.x = 1
else:
self.direction.x = 0
# Moving using inputs
def move(self, speed):
if self.direction.magnitude() != 0:
self.direction = self.direction.normalize()
self.rect.center += self.direction * speed
# updating drawing
def update(self):
self.input()
self.move(self.speed)
class Camera(pygame.sprite.Group):
def __init__(self):
super().__init__()
self.display_surface = pygame.display.get_surface()
self.offset = pygame.math.Vector2()
self.half_w = self.display_surface.get_size()[0] // 2
self.half_h = self.display_surface.get_size()[1] // 2
self.map = pygame.image.load('./map/level_data/level.png').convert_alpha()
self.rect = self.map.get_rect(topleft=(0, 0))
def custom_draw(self, player):
self.offset.x = player.rect.centerx - self.half_w
self.offset.y = player.rect.centery - self.half_h
ground_offset = self.rect.topleft - self.offset
self.display_surface.blit(self.map, ground_offset)
class Game():
def __init__(self):
# Settings
self.WIDTH = 1280
self.HEIGHT = 720
self.FPS = 60
pygame.init()
pygame.display.set_caption('BetterFortinite')
self.screen = pygame.display.set_mode((self.WIDTH, self.HEIGHT))
self.clock = pygame.time.Clock()
self.camera_group = Camera()
self.player = Player((100, 200), self.camera_group)
def game(self):
while True:
self.clock.tick(self.FPS)
self.screen.fill('black')
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# self.screen.fill("WHITE")
self.camera_group.custom_draw(self.player)
self.player.move(5)
self.player.update()
self.camera_group.draw(self.screen)
# self.camera_group.update()
pygame.display.update()
if __name__ in '__main__':
game = Game()
game.game()
I'm taking the center position of player rect minus half of the width size. Same with height and setting with it my offset. Then I'm setting my ground_offset as cords of topleft screen rect minus offset. What is wrong with this formula?

The problem is not with your formula, but with the code itsself. In the main game loop, you have:
self.player.move(5)
self.player.update()
While Player.update contains:
def update(self):
self.input()
self.move(self.speed)
As you can see, player.move is called twice. This means that the player is moved twice as much as intended and thus twice as fast as the camera, causing both to move at a different speed.
The solution to this problem would be to remove one of the calls of Player.move. I would remove the one in the main game loop as it uses a hardcoded value rather than the Player.speed constant, but it doesn't really matter which one you remove.

Related

How can I change the direction in which a bullet moves after it has been shot?

So, I'm trying to make a bullet curve in a spiral shape.
However, I end up with the bullets freezing in place and moving in a circle instead of forward.
Here is my bullet class code:
class Bullet(pygame.sprite.Sprite): #bullet class
def __init__(self, pos, img, angle=0, speed=10, acceleration=0, curve=10):
super().__init__()
#import image.
self.dir = angle
self.angle = (180 / math.pi) * -angle - 90
#turns towards the mouse
self.image = pygame.transform.rotate(img, self.angle)
self.rect = self.image.get_rect()
self.pos = list(pos)
self.spd = speed
self.acl = acceleration
self.curve = curve
self.wave = 0
#start lifetime of bullet
self.born = pygame.time.get_ticks()
def update(self):
#destroys itself if more than 10 secs have past from birth
self.live = pygame.time.get_ticks()
if self.live - self.born > 10000:
bullets.remove(self)
all_sprites_list.remove(self)
#update stats of bullet
self.dir += self.curve
self.spd += self.acl
#move the bullet
self.pos[0] += math.cos(self.dir) * self.spd
self.pos[1]+= math.sin(self.dir) * self.spd
self.rect.center = self.pos
Here is an example that creates spiral pathing bullets when right-clicking. Left-click generated bullets travel horizontally.
I have commented out the command to fill the frame so that you can see the path the bullet takes.
import pygame
import math
import random
width = 800
height = 600
pygame.init()
screen = pygame.display.set_mode((width, height))
clock = pygame.time.Clock()
class Bullet(pygame.sprite.Sprite):
"""Horizontally travelling bullet"""
def __init__(self, pos, color="grey16"):
super().__init__()
self.image = pygame.Surface((12, 5))
self.image.fill(color)
self.rect = self.image.get_rect(center=pos)
def move(self):
"""Move the bullet."""
self.rect.x += 5
def update(self):
"""Move and check for offscreen disposal"""
self.move()
# Remove the bullet if it flies up off the screen
if not 0 < self.rect.x < width + 12:
# print(f"Destroying {self} {self.rect.center} X")
self.kill() # Remove the sprite from all sprite groups.
elif not 0 < self.rect.y < height:
# print(f"Destroying {self} {self.rect.center} Y")
self.kill()
class SpiralBullet(Bullet):
"""Bullet sprite that moves in a spiral"""
def __init__(self, pos):
super().__init__(pos, "violetred")
# need to track the age to determine spiral position
self.start_tick = pygame.time.get_ticks()
self.start_pos = pos
self.angv = 0.1 # Angular Velocity
self.v = 2.0 # Velocity
def move(self):
"""Move in a spiral pattern"""
dt = pygame.time.get_ticks() - self.start_tick
if dt > 0:
dt = dt / 100 # slow it down
self.rect.x = (self.v * dt) * math.cos(self.angv * dt) + self.start_pos[0]
self.rect.y = (self.v * dt) * math.sin(self.angv * dt) + self.start_pos[1]
class Target(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.Surface((30, 50))
self.image.fill("orange")
self.rect = self.image.get_rect()
# create at the right of the screen
self.rect.x = width // 1.2
self.rect.y = random.randint(50, height - 50)
self.lives = 3
def update(self):
if self.lives <= 0:
self.kill() # Remove the sprite from all sprite groups.
# Create Groups for tracking sprites
all_sprites_list = pygame.sprite.Group()
bullets = pygame.sprite.Group()
targets = pygame.sprite.Group()
score = 0
screen.fill("turquoise") # initial fill incase we disable per frame fill
done = False
while not done:
## Handle Events
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
elif event.type == pygame.MOUSEBUTTONDOWN:
# Click a mouse button to instantiate a bullet.
if event.button == 3: # right-click for SpiralBullet
bullet = SpiralBullet(event.pos)
all_sprites_list.add(bullet)
bullets.add(bullet)
else:
bullet = Bullet(event.pos)
all_sprites_list.add(bullet)
bullets.add(bullet)
## Game State update
# Create a target if there aren't any
if not targets:
target = Target()
all_sprites_list.add(target)
targets.add(target)
# Call the update() method on all the sprites.
all_sprites_list.update()
# Check which bullets have collided with the Target.
collided_bullets = pygame.sprite.groupcollide(bullets, targets, True, False)
for bullet in collided_bullets:
score += 1 # Increment the score.
target.lives -= 1 # Decrement the lives.
## Draw a frame
# screen.fill("turquoise") # comment to see path
all_sprites_list.draw(screen)
## Update the display
pygame.display.flip()
pygame.display.set_caption(f"Score: {score}")
clock.tick(60)
pygame.quit()
This will show something like:
Here the lower orange target was created first and was hit by two spiral bullets and a horizontal bullet causing the higher target to spawn.

Pygame Delttime Function to go to the Right is 10 times slower than when I go to the left [duplicate]

This question already has answers here:
Pygame doesn't let me use float for rect.move, but I need it
(2 answers)
Closed 1 year ago.
Hello Stackoverflow Community,
could someone help me with my problem.
When I move to the left I am quite fast but when I want to go to the right it takes way to lang. I deleted the dt from my move function and the went the same speed. I changed the buttons but the problem seems only to occure when I use the +=. Does one of you dealt with the problem before and could help me?
import pygame
import time
import random
#0 = Menu, 1 = Game, 2 = Quit
game_state = 1
WHITE = (255, 255, 255)
class Player(pygame.sprite.Sprite):
speed = 100
def __init__(self, WIDTH):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("player.png")
self.rect = self.image.get_rect()
self.rect.center = (WIDTH / 2, 480)
def move(self, keys, dt):
if(keys[0]):
self.rect.x += self.speed * dt
print(self.speed)
print(dt)
print(self.rect.x)
if(keys[1]):
print(self.speed)
print(dt)
self.rect.x -= self.speed * dt
print(self.rect.x)
class Main():
prev_time = time.time()
dt = 0
#initalizing menu or game depending on variables
def __init__(self):
global game_state
while game_state !=2:
WIDTH, HEIGHT = 800, 600
screen = self.initialize_pygame("Alien Slaughter", WIDTH, HEIGHT)
self.all_sprites = pygame.sprite.Group()
self.player = Player(WIDTH)
self.all_sprites.add(self.player)
if(game_state == 1):
self.prev_time = time.time()
self.game(screen, WIDTH, HEIGHT)
#calculating deltatime
def calc_deltatime(self):
self.now = time.time()
self.dt = self.now - self.prev_time
self.prev_time = self.now
#initializing pygame and create window
def initialize_pygame(self, title, width, height):
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption(title)
icon = pygame.image.load("icon.png")
pygame.display.set_icon(icon)
pygame.init()
return screen
def handle_inputs(self, keys, event):
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_d:
keys[0] = True
if event.key == pygame.K_a:
keys[1] = True
if event.type == pygame.KEYUP:
if event.key == pygame.K_d:
keys[0] = False
if event.key == pygame.K_a:
keys[1] = False
def game(self, screen, width, height):
global game_state
BLACK = (100, 100, 100)
keys = [False, False]
#Game loop
while game_state == 1:
#Process input (events)
for event in pygame.event.get():
#Check for Closing windows
if event.type == pygame.QUIT:
game_state = 2
self.handle_inputs(keys, event)
self.calc_deltatime()
self.player.move(keys, self.dt)
#Update
self.all_sprites.update()
#Draw / render
screen.fill(BLACK)
self.all_sprites.draw(screen)
pygame.display.update()
game = Main()
Since pygame.Rect is supposed to represent an area on the screen, a pygame.Rect object can only store integral data.
The coordinates for Rect objects are all integers. [...]
The fraction part of the coordinates gets lost when the movement is added to the coordinates of the Rect object. If this is done every frame, the position error will accumulate over time.
If you want to store object positions with floating point accuracy, you have to store the location of the object in separate variables respectively attributes and to synchronize the pygame.Rect object. round the coordinate and assign it to the location of the rectangle:
class Player(pygame.sprite.Sprite):
speed = 100
def __init__(self, WIDTH):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("player.png")
self.rect = self.image.get_rect()
self.rect.center = (WIDTH / 2, 480)
self.x = self.rect.x
def move(self, keys, dt):
if keys[0]:
self.x += self.speed * dt
if keys[1]:
self.x -= self.speed * dt
self.rect.x = round(self.x)

Collision is not working Bullet vs Mob

I've tried numerous things to let my bullets collide with my mob, but it doesn't work. The bullet just goes straight through the mob. I also tried spritecollide and groupcollide codes, but they all failed. Maybe i'm putting my code in the wrong line or the wrong place. I also want the bullet and mob to be removed from the list.
import pygame
import random
import math
GRAD = math.pi / 180
black = (0,0,0)
Bulleti = pygame.image.load('bullet.png')
Monster = pygame.image.load('Monster1re.png')
class Config(object):
fullscreen = True
width = 1366
height = 768
fps = 60
class Player(pygame.sprite.Sprite):
maxrotate = 180
down = (pygame.K_DOWN)
up = (pygame.K_UP)
def __init__(self, startpos=(102,579), angle=0):
super().__init__()
self.pos = list(startpos)
self.image = pygame.image.load('BigShagHoofdzzz.gif')
self.orig_image = self.image
self.rect = self.image.get_rect(center=startpos)
self.angle = angle
def update(self, seconds):
pressedkeys = pygame.key.get_pressed()
if pressedkeys[self.down]:
self.angle -= 2
self.rotate_image()
if pressedkeys[self.up]:
self.angle += 2
self.rotate_image()
def rotate_image(self):
self.image = pygame.transform.rotate(self.orig_image, self.angle)
self.rect = self.image.get_rect(center=self.rect.center)
class Mob(pygame.sprite.Sprite):
def __init__(self, image):
super().__init__()
self.image = image
self.rect = self.image.get_rect()
self.rect.x = 1400
self.rect.y = random.randrange(500,600)
self.speedy = random.randrange(-8, -1)
def update(self):
self.rect.x += self.speedy
if self.rect.x < -100 :
self.rect.x = 1400
self.speedy = random.randrange(-8, -1)
class Bullet(pygame.sprite.Sprite):
"""This class represents the bullet."""
def __init__(self, pos, angle, image):
super().__init__()
self.image = image
self.image = pygame.transform.rotate(self.image, angle)
self.rect = self.image.get_rect()
speed = 15
self.velocity_x = math.cos(math.radians(-angle)) * speed
self.velocity_y = math.sin(math.radians(-angle)) * speed
self.pos = list(pos)
def update(self):
""" Move the bullet. """
self.pos[0] += self.velocity_x
self.pos[1] += self.velocity_y
self.rect.center = self.pos
player = Player()
#this is the mob group
mobs = []
for x in range(0,10):
mob = Mob(Monster)
mobs.append(mob)
print(mobs)
#sprite lists
bullet_list = pygame.sprite.Group()
all_sprites_list = pygame.sprite.Group()
allgroup = pygame.sprite.LayeredUpdates()
allgroup.add(player)
for mob in mobs:
all_sprites_list.add(mob)
def main():
#game
pygame.mixer.pre_init(44100, -16, 1, 512)
pygame.mixer.init()
pygame.init()
screen=pygame.display.set_mode((Config.width, Config.height),
pygame.FULLSCREEN)
background = pygame.image.load('BGGameBig.png')
sound = pygame.mixer.Sound("shoot2.wav")
clock = pygame.time.Clock()
FPS = Config.fps
mainloop = True
while mainloop:
millisecond = clock.tick(Config.fps)
for event in pygame.event.get():
if event.type == pygame.QUIT:
mainloop = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
mainloop = False
if event.key == pygame.K_SPACE: #Bullet schiet knop op space
# Pass the position and angle of the player.
bullet = Bullet(player.rect.center, player.angle,
Bulleti)
all_sprites_list.add(bullet)
bullet_list.add(bullet)
sound.play()
if event.key == pygame.K_ESCAPE:
mailoop = False
pygame.display.set_caption("hi")
allgroup.update(millisecond)
all_sprites_list.update()
for bullet in bullet_list:
if bullet.rect.x > 1380:
bullet_list.remove(bullet)
all_sprites_list.remove(bullet)
#this is the code for collission
hits = pygame.sprite.groupcollide(bullet_list, mobs, True, True)
screen.blit(background, (0,0))
allgroup.draw(screen)
all_sprites_list.draw(screen)
pygame.display.flip()
if __name__ == '__main__':
main()
pygame.quit()
if anyone could help me out on this one it would really be appreciated. I spent alot of time working on the solution but I haven't found any yet. Watched alot of youtubers and did the same thing but it just won't work.
I get a different error when I run the program, an AttributeError caused by this line hits = pygame.sprite.groupcollide(bullet_list, mobs, True, True). That happens because the mobs list should be a pygame.sprite.Group.
mobs = pygame.sprite.Group()
for x in range(0,10):
mob = Mob(Monster)
mobs.add(mob)
After I changed this part of the code, it worked correctly.

how to rotate a bullet according to the player's rotation

I've finally figured out how to shoot bullets but now I want to rotate the origin of the bullets on the rotation of the players head. Now it's only shooting straight on the x line. The mobs are working fine. I only need to add in collision and the bullet that is rotating on the player's angle. I will do the collision myself although If anyone could hint me it would be appreciated. My main focus right now is to rotate the bullet according to the player's angle and 'kill' the bullet when it flies off screen.
import pygame
import random
import math
GRAD = math.pi / 180
black = (0,0,0)
class Config(object):
fullscreen = True
width = 1366
height = 768
fps = 60
class Player(pygame.sprite.Sprite): #player class
maxrotate = 180
down = (pygame.K_DOWN)
up = (pygame.K_UP)
def __init__(self, startpos=(102,579), angle=0):
super().__init__()
self.pos = list(startpos)
self.image = pygame.image.load('BigShagHoofdzzz.gif')
self.orig_image = self.image
self.rect = self.image.get_rect(center=startpos)
self.angle = angle
def update(self, seconds):
pressedkeys = pygame.key.get_pressed()
if pressedkeys[self.down]:
self.angle -= 2
self.rotate_image()
if pressedkeys[self.up]:
self.angle += 2
self.rotate_image()
def rotate_image(self):#rotating player image
self.image = pygame.transform.rotate(self.orig_image, self.angle)
self.rect = self.image.get_rect(center=self.rect.center)
class Mob(pygame.sprite.Sprite):#monster sprite
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load('Monster1re.png')
self.rect = self.image.get_rect()
self.rect.x = 1400
self.rect.y = random.randrange(500,600)
self.speedy = random.randrange(-8, -1)
def update(self):
self.rect.x += self.speedy
if self.rect.x < -100 :
self.rect.x = 1400
self.speedy = random.randrange(-8, -1)
class Bullet(pygame.sprite.Sprite):#bullet sprite needs to rotate according to player's angle.
""" This class represents the bullet . """
def __init__(self):
# Call the parent class (Sprite) constructor
super().__init__()
self.image = pygame.image.load('lols.png').convert()
self.image.set_colorkey(black)
self.rect = self.image.get_rect()
def update(self):
""" Move the bullet. """
self.rect.x += 10
#end class
player = Player()
mobs = []
for x in range(0,10):
mob = Mob()
mobs.append(mob)
print(mobs)
all_sprites_list = pygame.sprite.Group()
allgroup = pygame.sprite.LayeredUpdates()
allgroup.add(player)
for mob in mobs:
all_sprites_list.add(mob)
def main():
#game
pygame.mixer.pre_init(44100, -16, 1, 512)
pygame.mixer.init()
pygame.init()
screen=pygame.display.set_mode((Config.width, Config.height),
pygame.FULLSCREEN)
background = pygame.image.load('BGGameBig.png')
sound = pygame.mixer.Sound("shoot2.wav")
bullet_list = pygame.sprite.Group
clock = pygame.time.Clock()
FPS = Config.fps
mainloop = True
while mainloop:
millisecond = clock.tick(Config.fps)
for event in pygame.event.get():
if event.type == pygame.QUIT:
mainloop = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
mainloop = False
if event.key == pygame.K_SPACE: #Bullet schiet knop op space
bullet = Bullet()
bullet.rect.x = player.rect.x
bullet.rect.y = player.rect.y
all_sprites_list.add(bullet)
bullet_list.add(bullet)
sound.play()
if event.key == pygame.K_ESCAPE:
mailoop = False
pygame.display.set_caption("hi")
allgroup.update(millisecond)
all_sprites_list.update()
screen.blit(background, (0,0))
allgroup.draw(screen)
all_sprites_list.draw(screen)
pygame.display.flip()
if __name__ == '__main__':
main()
pygame.quit()
So It needs to rotate on the players self.angle which is updated when pressing key up or key down.
You need to use trigonometry or vectors to calculate the velocity of the bullet (I use trig here). Pass the angle of the player to the Bullet and then use math.cos and math.sin with the negative angle to get the direction of the bullet and scale it by the desired speed. The actual position has to be stored in a list or vector, because pygame.Rects can only have ints as their coordinates.
class Bullet(pygame.sprite.Sprite):
"""This class represents the bullet."""
def __init__(self, pos, angle):
super().__init__()
# Rotate the image.
self.image = pygame.transform.rotate(your_bullet_image, angle)
self.rect = self.image.get_rect()
speed = 5 # 5 pixels per frame.
# Use trigonometry to calculate the velocity.
self.velocity_x = math.cos(math.radians(-angle)) * speed
self.velocity_y = math.sin(math.radians(-angle)) * speed
# Store the actual position in a list or a vector.
self.pos = list(pos)
def update(self):
""" Move the bullet. """
self.pos[0] += self.velocity_x
self.pos[1] += self.velocity_y
# Update the position of the rect as well.
self.rect.center = self.pos
# In the event loop.
if event.key == pygame.K_SPACE:
# Pass the position and angle of the player.
bullet = Bullet(player.rect.center, player.angle)
all_sprites_list.add(bullet)
bullet_list.add(bullet)

How to add a Collision in Pygame

i'm making a game about a car trying not to collide with pedestrian car.
I'm trying to add a collision to the user_car(aka Player class) with enemy(aka pedestrian_cars class), but i'm not exactly sure where(while loop?) and how to do it. Some variables maybe be bad but I will fix them later.
My program:
import pygame, random, math, sys
from pygame.locals import *
class Player(pygame.sprite.Sprite):
def __init__(self, starty):
pygame.sprite.Sprite.__init__(self)
# Images
self.aliveImage = pygame.image.load("playercar.png").convert_alpha()
#self.deadImage = pygame.image.load("data/PlayerExplode.png").convert_alpha()
self.image = self.aliveImage
self.rect = self.image.get_rect()
self.rect.x = 200
self.rect.y = starty - self.rect.height
self.speed = 7
self.dead = False
# Explode if you get hit, lose a life
def explode(self):
if not self.dead:
self.dead = True
self.image = self.deadImage
pygame.mixer.stop()
self.channel = self.explodeSound.play()
game.playerShots.empty()
game.enemyShots.empty()
game.wave.mship.empty()
game.lives.update(-1)
class pedestrian_cars(pygame.sprite.Sprite):
def __init__(self, starty,startx):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("pedcar.png").convert_alpha()
self.rect = self.image.get_rect()
self.rect.y = starty - self.rect.height
self.rect.x = startx - self.rect.width
self.delta_y = 5 # 5
self.gravity = .5 #.5
self.has_spawned = False
def update(self):
self.rect.y += self.delta_y
def spawn(self):
if self.rect.y == 480 or self.has_spawned == False:
self.has_spawned = True
self.rect.x = random.randint(60,300)
self.rect.y = -10
def main():
""" Set up the game and run the main game loop """
pygame.mixer.pre_init(44100, -16, 2, 2048)
pygame.init() # prepare the pygame module for use
surfaceSz = 480 # Desired physical surface size, in pixels.
# Create surface of (width, height), and its window.
main_surface = pygame.display.set_mode((surfaceSz, surfaceSz))
#SPRITES###############################################################
user_car = Player(450)
enemy = pedestrian_cars(10,200)
#SPRITES################################################################
background_image = pygame.image.load("background2.png")
all_sprites = pygame.sprite.Group()
user_car.add(all_sprites)
enemy.add(all_sprites)
clock = pygame.time.Clock()
b1 = "background2.png"
back = pygame.image.load(b1).convert()
back2 = pygame.image.load(b1).convert()
y = 0
screenWidth = 600
screenHeight = 480
#Sound/Music#####################################
pygame.mixer.music.load("stilldre.wav")
pygame.mixer.music.play(-1)
#-################################################
while True:
ev = pygame.event.poll() # look for any event
if ev.type == pygame.QUIT: # window close button clicked?
break # ... leave game loop
sys.exit()
if not user_car.dead:
# Move the player
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
user_car.rect.x = max(user_car.rect.x - user_car.speed, 116-user_car.rect.width)
elif keys[pygame.K_RIGHT]:
user_car.rect.x = min(user_car.rect.x + user_car.speed, 395-user_car.rect.width)
else:
# Go back to playing after the explosion sound finishes
if not self.channel.get_busy():
self.image = self.aliveImage
self.dead = False
self.rect.x = 200
# Update your game objects and data structures here...
all_sprites.update()
enemy.spawn()
main_surface.fill((0,200,255))
main_surface.blit(background_image, (0, 0))
main_surface.blit(back, (0,y))
main_surface.blit(back2,(0,y-screenHeight))
y = y + 8
if y == screenWidth:
y = 0
## if enemy.alive.x ==
## msElapsed = clock.tick(100)
## pygame.display.flip()
all_sprites.draw(main_surface)
# Now the surface is ready, tell pygame to display it!
pygame.display.flip()
clock.tick(200)
msElapsed = clock.tick(100)
pygame.quit() # once we leave the loop, close the window.
main()
You can simply check if the rects of your objects overlap with colliderect:
while True:
...
if user_car.rect.colliderect(enemy.rect):
do_something()
...

Categories