How Can I Make An Arrow Image Move Rotated Direction? [duplicate] - python
This question already has answers here:
How can you rotate the sprite and shoot the bullets towards the mouse position?
(1 answer)
calculating direction of the player to shoot pygame
(1 answer)
Shooting a bullet in pygame in the direction of mouse
(2 answers)
Closed 2 years ago.
I have an arrow image that rotates left and right VIDEO as you can see in the video when I click my arrow stops rotating and I want it to move the direction it stopped rotating on how would I do that?
right now I only have it so when I click the rotation stops but not really sure how I could make it move the direction it stopped rotating on
I tried to make it so when the player clicks the arrow starts to move but its the same thing it doesnt move towards like the rotated place it will just move my arrow down VIDEO
rotating_arrow = True
move = False
# our main loop
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.MOUSEBUTTONDOWN:
rotating_arrow = False
move = True
if move:
move_angle = bow2.angle + 15 # The arrow is painted approximately 15° downwards
speed = 20
move_vec = pygame.math.Vector2(speed, 0).rotate(move_angle)
bow2.x += move_vec.x
bow2.y += move_vec.y
bow2.rect.topleft = round(bow2.x), round(bow2.y)
this is how my rotated image is set
def blitRotate(surf, image, pos, originPos, angle):
# calcaulate the axis aligned bounding box of the rotated image
w, h = image.get_size()
sin_a, cos_a = math.sin(math.radians(angle)), math.cos(math.radians(angle))
min_x, min_y = min([0, sin_a*h, cos_a*w, sin_a*h + cos_a*w]), max([0, sin_a*w, -cos_a*h, sin_a*w - cos_a*h])
# calculate the translation of the pivot
pivot = pygame.math.Vector2(originPos[0], -originPos[1])
pivot_rotate = pivot.rotate(angle)
pivot_move = pivot_rotate - pivot
# calculate the upper left origin of the rotated image
origin = (pos[0] - originPos[0] + min_x - pivot_move[0], pos[1] - originPos[1] - min_y + pivot_move[1])
# get a rotated image
rotated_image = pygame.transform.rotate(image, angle)
# rotate and blit the image
surf.blit(rotated_image, origin)
my arrow class
class arrow:
def __init__(self,x,y,height,width,color):
self.x = x
self.y = y
self.height = height
self.width = width
self.color = color
self.shootsright = pygame.image.load("ner.png")
self.image = self.shootsright
self.rect = self.image.get_rect(center = (self.x, self.y))
self.look_at_pos = (self.x, self.y)
self.isLookingAtPlayer = False
self.look_at_pos = (x,y)
self.angle = 0
self.gun_size = self.image.get_size()
self.pivot = (8, self.gun_size[1]//2)
self.rect = pygame.Rect(x,y,height,width)
def draw(self):
blitRotate(window, self.image, self.rect.center, self.pivot, self.angle)
pygame.draw.rect(window,self.color,self.rect)
If you want to fire a bullet in a certain direction, the direction is defined the moment the bullet is fired, but it does not change continuously. This means that after the arrow is fired, the angle will not change.
Compute the direction of the arrow by the trigonometric functions sin and cos. Define the speed of the arrow. Change the position attributes (x, y) of the arrow in each frame:
speed = 20
self.x += speed * math.cos(math.radians(move_angle))
self.y -= speed * math.sin(math.radians(move_angle))
Update the rect attribute:
self.rect.topleft = round(self.x), round(self.y)
Since the arrow picture is painted at a certain angle, the motion angle may need to be corrected:
move_angle = self.angle - 15 # The arrow is painted approximately 15° downwards
Complete arrow.draw method:
class arrow:
# [...]
def draw(self):
move_angle = self.angle - 15 # The arrow is painted approximately 15° downwards
speed = 20
self.x += speed * math.cos(math.radians(move_angle))
self.y -= speed * math.sin(math.radians(move_angle))
self.rect.topleft = round(self.x), round(self.y)
blitRotate(window, self.image, self.rect.center, self.pivot, self.angle)
pygame.draw.rect(window,self.color,self.rect)
Related
When moving player towards mouse, players direction isn't constant [duplicate]
This question already has answers here: Pygame doesn't let me use float for rect.move, but I need it (2 answers) Pygame diagonal movement not at correct angle (1 answer) Closed 8 months ago. When holding the left mouse button down, I would like the player to move towards the mouse position. This does work however, the direction the player travels in isn't always constant and doesn't move straight towards the mouse. Here is the player class: class Player: def __init__(self, x, y): self.image = pygame.Surface((30, 30)) self.rect = self.image.get_rect(center = (x, y)) self.speed = 5 def move_player(self, x, y): mx, my = pygame.mouse.get_pos() self.dirx, self.diry = mx - x, my - y length = math.hypot(*(self.dirx, self.diry)) if length == 0.0: self.dirx, self.diry = 0, -1 else: self.dirx, self.diry = self.dirx/length, self.diry/length self.rect.x += self.dirx * self.speed self.rect.y += self.diry * self.speed def draw_player(self, screen, colour): self.image.fill(colour) screen.blit(self.image, (self.rect.x, self.rect.y)) In the while loop I move the player: if mouse[0]: player.move_player(player.rect.x, player.rect.y) player.draw_player(screen, (255, 0, 0))
Move Character with Vector
I am teaching myself pygame and am looking at making my character able to rotate and then move in the direction they are facing. I can do the rotation but cannot get the character to move in the direction the image is then facing. The code is on Trinket HERE class Bob(pygame.sprite.Sprite): def __init__(self, color , height , width): super().__init__() self.image = pygame.Surface([width , height]) self.image.fill(BLACK) self.image.set_colorkey(BLACK) #Loading the image for the character self.img = pygame.image.load("char.jfif") #creating a copy of the image self.img_orig = self.img.copy() #defining the starting angle of the character image self.angle = 0 self.velocity = 5 self.rect = self.img_orig.get_rect() def moveLeft(self): self.angle += 1 self.img = pygame.transform.rotate(self.img_orig, self.angle) def moveRight(self): self.rect.x += self.velocity if self.rect.x > 485: self.rect.x = 485 while run: for event in pygame.event.get(): if event.type == pygame.QUIT: run = False keys = pygame.key.get_pressed() if keys[pygame.K_UP]: pSprite.moveForward() if keys[pygame.K_DOWN]: pSprite.moveDown() if keys[pygame.K_LEFT]: pSprite.moveLeft() if keys[pygame.K_RIGHT]: pSprite.moveRight() #---- Game Logic Here #--- Drawing Code Here #Reset the screen to blank screen.fill(BLUE) #Draw Play Area #Draw Sprites screen.blit(pSprite.img,(pSprite.rect.x, pSprite.rect.y))
You can use pygame's Vector2 class instead of calculating the position of your sprite yourself. I also suggest to let the sprite itself handle its movement instead of doing so in the main loop and using a clock for constant framerates and easy control of the speed of your sprites. You also probably want to use an image format with alpha channel (like PNG). Here's a simple example: import pygame class Actor(pygame.sprite.Sprite): def __init__(self, pos, *grps): super().__init__(*grps) self.image = pygame.image.load('char.png').convert_alpha() self.image_org = self.image.copy() self.rect = self.image.get_rect(center=pos) self.pos = pygame.Vector2(pos) self.direction = pygame.Vector2((0, -1)) def update(self, events, dt): pressed = pygame.key.get_pressed() # if a is pressed, rotate left with 360 degress per second if pressed[pygame.K_a]: self.direction.rotate_ip(dt * -360) # if d is pressed, rotate right with 360 degress per second if pressed[pygame.K_d]: self.direction.rotate_ip(dt * 360) # check if should move forward or backward movement = 0 if pressed[pygame.K_w]: movement = 1 if pressed[pygame.K_s]: movement = -1 movement_v = self.direction * movement if movement_v.length() > 0: movement_v.normalize_ip() # move 100px per second in the direction we're facing self.pos += movement_v * dt * 100 # rotate the image self.image = pygame.transform.rotate(self.image_org, self.direction.angle_to((0, -1))) self.rect = self.image.get_rect(center=self.pos) def main(): pygame.init() screen = pygame.display.set_mode((600, 480)) sprites = pygame.sprite.Group() Actor((100, 100), sprites) clock, dt = pygame.time.Clock(), 0 while True: events = pygame.event.get() for e in events: if e.type == pygame.QUIT: return screen.fill('grey') sprites.draw(screen) sprites.update(events, dt) pygame.display.flip() dt = clock.tick(60) / 1000 main() char.png
Rotate the player around its center (see How do I rotate an image around its center using PyGame?): self.angle += 1 self.img = pygame.transform.rotate(self.img_orig, self.angle) self.rect = self.img.get_rect(center = self.rect.center) Use an attribute x and y to store the position of the player with floating point accuracy. class Bob(pygame.sprite.Sprite): def __init__(self, color , height , width): # [...] self.x, self.y = self.rect.center Compute the direction of the player dependent on the angle with the trgonometric function math.sin and math.cos. Change the position attributes and update the rect attribute: self.x += self.velocity * math.cos(math.radians(self.angle + 90)) self.y -= self.velocity * math.sin(math.radians(self.angle + 90)) self.rect.center = round(self.x), round(self.y) The y-axis needs to be reversed (-dy) as the y-axis is generally pointing up, but in the PyGame coordinate system the y-axis is pointing down. In addition, a correction angle must be deducted (+ 90). Since the "angle" is 0 ° when the sprite is looking up, you need to add 90 ° to the angle for the calculation of the direction vector. See also te in pygame while moving with the keys](How to turn the sprite in pygame while moving with the keys. Class Bob: import pygame import math BLACK = (0,0,0) class Bob(pygame.sprite.Sprite): def __init__(self, color , height , width): super().__init__() self.image = pygame.Surface([width , height]) self.image.fill(BLACK) self.image.set_colorkey(BLACK) #Loading the image for the character self.img = pygame.image.load("char.jfif") #creating a copy of the image self.img_orig = self.img.copy() #defining the starting angle of the character image self.angle = 0 self.velocity = 5 self.rect = self.img_orig.get_rect() self.x, self.y = self.rect.center def rotate(self, change_angle): self.angle += change_angle self.img = pygame.transform.rotate(self.img_orig, self.angle) self.rect = self.img.get_rect(center = self.rect.center) def move(self, distance): self.x += distance * math.cos(math.radians(self.angle + 90)) self.y -= distance * math.sin(math.radians(self.angle + 90)) self.rect.center = round(self.x), round(self.y) def moveLeft(self): self.rotate(1) def moveRight(self): self.rotate(-1) def moveForward(self): self.move(self.velocity) def moveDown(self): self.move(-self.velocity) When setting the starting position of the player, you need to set the x, y and rect attribute: pSprite = Bob(WHITE , 25,25) pSprite.rect.x = 50 pSprite.rect.y = 50 pSprite.x, pSprite.y = pSprite.rect.center
Shooting a bullet in pygame in the direction of mouse
I just cant figure out why my bullet is not working. I made a bullet class and here it is: class Bullet: def __init__(self): self.x = player.x self.y = player.y self.height = 7 self.width = 2 self.bullet = pygame.Surface((self.width, self.height)) self.bullet.fill((255, 255, 255)) Now I added several functions in my game class and here is the new code: class Game: def __init__(self): self.bullets = [] def shoot_bullet(self): if self.bullets: for bullet in self.bullets: rise = mouse.y - player.y run = mouse.x - player.x angle = math.atan2(rise, run) bullet.x += math.cos(angle) bullet.y += math.sin(angle) pygame.transform.rotate(bullet.bullet, -math.degrees(angle)) D.blit(bullet.bullet, (bullet.x, bullet.y)) def generate_bullet(self): if mouse.is_pressed(): self.bullets.append(Bullet()) What I was expecting the code to do was a Bullet() would get added to game.bullets every time I pressed the mouse button, then game.shoot_bullet would calculate the angle between the player and the mouse and shoot the bullet accordingly in the direction of the mouse. However, the result is a complete mess and the bullets actually don't rotate and don't move. They get generated and move weirdly to the left of the screen. I am not sure if I have messed up something or the method I have used is completely wrong.
First of all pygame.transform.rotate does not transform the object itself, but creates a new rotated surface and returns it. If you want to fire a bullet in a certain direction, the direction is defined the moment the bullet is fired, but it does not change continuously. When the bullet is fired, set the starting position of the bullet and calculate the direction vector to the mouse position: self.pos = (x, y) mx, my = pygame.mouse.get_pos() self.dir = (mx - x, my - y) The direction vector should not depend on the distance to the mouse, but it has to be a Unit vector. Normalize the vector by dividing by the Euclidean distance length = math.hypot(*self.dir) if length == 0.0: self.dir = (0, -1) else: self.dir = (self.dir[0]/length, self.dir[1]/length) Compute the angle of the vector and rotate the bullet. In general, the angle of a vector can be computed by atan2(y, x). The y-axis needs to be reversed (atan2(-y, x)) as the y-axis generally points up, but in the PyGame coordinate system the y-axis points down (see How to know the angle between two points?): angle = math.degrees(math.atan2(-self.dir[1], self.dir[0])) self.bullet = pygame.Surface((7, 2)).convert_alpha() self.bullet.fill((255, 255, 255)) self.bullet = pygame.transform.rotate(self.bullet, angle) To update the position of the bullet, it is sufficient to scale the direction (by a velocity) and add it to the position of the bullet: self.pos = (self.pos[0]+self.dir[0]*self.speed, self.pos[1]+self.dir[1]*self.speed) To draw the rotated bullet in the correct position, take the bounding rectangle of the rotated bullet and set the center point with self.pos (see How do I rotate an image around its center using PyGame?): bullet_rect = self.bullet.get_rect(center = self.pos) surf.blit(self.bullet, bullet_rect) See also Shoot bullets towards target or mouse Minimal example: repl.it/#Rabbid76/PyGame-FireBulletInDirectionOfMouse import pygame import math pygame.init() window = pygame.display.set_mode((500, 500)) clock = pygame.time.Clock() class Bullet: def __init__(self, x, y): self.pos = (x, y) mx, my = pygame.mouse.get_pos() self.dir = (mx - x, my - y) length = math.hypot(*self.dir) if length == 0.0: self.dir = (0, -1) else: self.dir = (self.dir[0]/length, self.dir[1]/length) angle = math.degrees(math.atan2(-self.dir[1], self.dir[0])) self.bullet = pygame.Surface((7, 2)).convert_alpha() self.bullet.fill((255, 255, 255)) self.bullet = pygame.transform.rotate(self.bullet, angle) self.speed = 2 def update(self): self.pos = (self.pos[0]+self.dir[0]*self.speed, self.pos[1]+self.dir[1]*self.speed) def draw(self, surf): bullet_rect = self.bullet.get_rect(center = self.pos) surf.blit(self.bullet, bullet_rect) bullets = [] pos = (250, 250) run = True while run: clock.tick(60) for event in pygame.event.get(): if event.type == pygame.QUIT: run = False if event.type == pygame.MOUSEBUTTONDOWN: bullets.append(Bullet(*pos)) for bullet in bullets[:]: bullet.update() if not window.get_rect().collidepoint(bullet.pos): bullets.remove(bullet) window.fill(0) pygame.draw.circle(window, (0, 255, 0), pos, 10) for bullet in bullets: bullet.draw(window) pygame.display.flip()
I noticed that the cycle where you checking the condition if lenghts is equal to 0 it doesn't really make any sense. Of-course the value of sqrt(0) is always 0, but how is this even possible in reality to get? 0% (i guess) So, while its looking for a path by calculate a hypotenuse if length == 0.0: self.dir = (0, -1) In which scenario where it returns 0 is possible ? P.S. if i am missing any thing feel free to suggest
Pygame move drawn rect(not image) in the same way as the player, including rotation [duplicate]
This question already has answers here: How do I rotate an image around its center using Pygame? (6 answers) How can you rotate an image around an off center pivot in Pygame (1 answer) Closed 2 years ago. I'm trying to create a laser beam for my starship, this laser beam is a drawn rect and not an image, I move the starship with "w-a-s-d" and aim with the mouse, I created a class "Laser" and I've managed to make it aim in the same direction as the player. In addition to rotating, the beam should also move to stay attached to the ship, but I can not understand how to do it. class Player: #inizialize the player def __init__(self, x, y, player): self.x = x self.y = y self.image = player self.is_shooting = False self.original_player_image = player self.angle = 0 #move the player def movePlayer(self): if key[0]: self.x -= 10 elif key[1]: self.x += 10 if key[2]: self.y -= 10 elif key[3]: self.y += 10 #check borders if self.x <= 0: self.x = 0 if self.x + rock_image.get_width() >= display_width: self.x = display_width - player_image.get_width() if self.y <= 0: self.y = 0 if self.y + player_image.get_height() >= display_height: self.y = display_height - player_image.get_height() #rotate the player where the mouse is aiming def rotate(self): mouse_x, mouse_y = pygame.mouse.get_pos() rel_x, rel_y = mouse_x - self.x, mouse_y - self.y self.angle = (180 / math.pi) * -math.atan2(rel_y, rel_x) - 90 self.image = pygame.transform.rotate(self.original_player_image, int(self.angle)) self.rect = self.image.get_rect() #draw the player def drawPlayer(self): screen.blit(self.image, (self.x, self.y)) class Laser: def __init__(self, player_x, player_y): self.x = player_x self.y = player_y self.original_image = pygame.Surface((5, 150)) self.original_image.set_colorkey( (0,0,0) ) self.original_image.fill( (255,0,0) ) self.copy_image = self.original_image.copy() self.copy_image.set_colorkey( (0,0,0) ) self.rect = self.copy_image.get_rect() self.rect.center = self.x + player_image.get_width()//2, self.y - 75 self.new_image = pygame.Surface((5, 150)) def continueDrawLaser(self): if laser_bool: screen.blit(self.new_image, self.rect) def rotate(self): mouse_x, mouse_y = pygame.mouse.get_pos() rel_x, rel_y = mouse_x - player1.x, mouse_y - player1.y angle = (180 / math.pi) * -math.atan2(rel_y, rel_x) - 85 vel_x = math.cos(angle) vel_y = math.sin(angle) self.new_image = pygame.transform.rotate(self.original_image, angle) self.rect = self.new_image.get_rect() self.rect.center = player1.x + vel_x, player1.y + vel_y First there is the Player class(starship) The second one is the Laser class(laser beam) This is what I get: If you need the whole code I posted it here: https://pastebin.com/jnYifErX To let you test the code I have eliminated all the useless things and left only the player with the laser beam, so you have to download only the spaceship to test the code,here the shortened code: https://pastebin.com/VTbuCZY4 Link to download the spaceship: https://www.flaticon.com/free-icon/spaceship_1114780?term=space%20ship&page=1&position=57
In the answer to How do I rotate an image around its center using Pygame? is presented an algorithm to rotate an image around a pivot. Use the algorithm to implement the function rotate in the class Laser, dependent on the orientation and position of player1 class Laser: # [...] def rotate(self): # get rectangle of player and laser, as if the angle would be 0 player_rect = player1.original_player_image.get_rect(topleft = (player1.x, player1.y)) laser_rect = self.original_image.get_rect(midbottom = player_rect.midtop) self.angle = player1.angle pos = player_rect.center pivotPos = [pos[0] - laser_rect.x, pos[1] - laser_rect.y] # calcaulate the axis aligned bounding box of the rotated image w, h = self.original_image.get_size() box = [pygame.math.Vector2(p) for p in [(0, 0), (w, 0), (w, -h), (0, -h)]] box_rotate = [p.rotate(self.angle) for p in box] min_box = (min(box_rotate, key=lambda p: p[0])[0], min(box_rotate, key=lambda p: p[1])[1]) max_box = (max(box_rotate, key=lambda p: p[0])[0], max(box_rotate, key=lambda p: p[1])[1]) # calculate the translation of the pivot pivot = pygame.math.Vector2(pivotPos[0], -pivotPos[1]) pivot_rotate = pivot.rotate(self.angle) pivot_move = pivot_rotate - pivot # calculate the upper left origin of the rotated image origin = (pos[0] - pivot[0] + min_box[0] - pivot_move[0], pos[1] + pivot[1] - max_box[1] + pivot_move[1]) # get a rotated image self.new_image = pygame.transform.rotate(self.original_image, self.angle) # get new rectangle self.rect = self.new_image.get_rect(topleft = (round(origin[0]), round(origin[1]))) Further mote, you've to ensure that the rotated spaceship is correctly placed. Calculate the center of the un-rotated spaceship and apply the center to the rotated spaceship. Use the .rect attribute of the spaceship to blit: class Player: # [...] # rotate the player where the mouse is aiming def rotate(self): mouse_x, mouse_y = pygame.mouse.get_pos() rel_x, rel_y = mouse_x - self.x, mouse_y - self.y self.angle = (180 / math.pi) * -math.atan2(rel_y, rel_x) - 90 self.image = pygame.transform.rotate(self.original_player_image, int(self.angle)) orig_center = self.original_player_image.get_rect(topleft = (self.x, self.y)).center self.rect = self.image.get_rect(center = orig_center) # draw the player def drawPlayer(self): screen.blit(self.image, self.rect.topleft) Of course every time when the player is rotated, then the laser has to be rotated, too: player1.movePlayer() player1.rotate() laser1.rotate()
pygame/python wont detect collision between sprites
im trying to detect a collision between pacman and the boxes, but its not detecting any collision, any help or advice? at the moment ive tried creating a list of instances but that hasnt worked, i dont know what else to do. also its telling me to add more detail but i dont really know what i can add to be honest, sorry import pygame import os import sys #intialise the game pygame.init() screen = pygame.display.set_mode((448, 576)) done = False y = 320 x = 216 #sets up clock and loads pacman image clock = pygame.time.Clock() PACMANSPRITE = pygame.image.load("pacman.png").convert_alpha() #gets pacman intro music, sets music to lower volume then plays it pygame.mixer.music.load('pacman_beginning.WAV') pygame.mixer.music.set_volume(0.01) pygame.mixer.music.play(0) #box class, used for boxes to border pacmans map class boxcollisions(pygame.sprite.Sprite): def __init__(self, x, y): self.y = y self.x = x self.rect = pygame.Rect(self.x, self.y, 15, 15) self.color = (0, 128, 255) def draw(self, screen): pygame.draw.rect(screen, self.color, self.rect) #pacmans class class pacman(pygame.sprite.Sprite): def __init__(self, image, x, y): self.image = image self.y=y self.x=x self.rect = self.image.get_rect() self.rect.left = self.x self.rect.top = self.y self.rect.width=16 self.rect.height=16 # move pacman def movement(self): pressed= pygame.key.get_pressed() if pressed[pygame.K_UP]: self.y -= 2 if pressed[pygame.K_DOWN]: self.y += 2 if pressed[pygame.K_LEFT]: self.x -= 2 if pressed[pygame.K_RIGHT]: self.x += 2 def draw(self, surface): """ Draw on surface """ # blit yourself at your current position surface.blit(self.image, (self.x, self.y)) #instances the pacman class sprite = pacman(PACMANSPRITE, x ,y) #main game loop while not done: for event in pygame.event.get(): if event.type == pygame.QUIT: done = True pygame.quit() sys.exit() screen.fill((100,0,0)) #co-ordinates for boxes to set up map boundaries boundaries=[ [], [], [], [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28], [1,14,15,28], #5 [1,3,4,5,6,8,9,10,11,12,14,15,17,18,19,20,21,23,24,25,26,28], [1,3,4,5,6,8,9,10,11,12,14,15,17,18,19,20,21,23,24,25,26,28], [1,3,4,5,6,8,9,10,11,12,14,15,17,18,19,20,21,23,24,25,26,28], [1,28], [1,3,4,5,6,8,9,11,12,13,14,15,16,17,18,20,21,23,24,25,26,28], #10 [1,3,4,5,6,8,9,11,12,13,14,15,16,17,18,20,21,23,24,25,26,28], [1,8,9,14,15,20,21,28], [1,2,3,4,5,6,8,9,10,11,12,14,15,17,18,19,20,21,23,24,25,26,27,28], [1,2,3,4,5,6,8,9,10,11,12,14,15,17,18,19,20,21,23,24,25,26,27,28], [6,8,9,20,21,23], #15 [6,8,9,11,12,13,14,15,16,17,18,20,21,23], [1,2,3,4,5,6,8,9,11,12,13,14,15,16,17,18,20,21,23,24,25,26,27,28], [1,11,12,13,14,15,16,17,18,28], [1,2,3,4,5,6,8,9,11,12,13,14,15,16,17,18,20,21,23,24,25,26,27,28], [6,8,9,11,12,13,14,15,16,17,18,20,21,23,24,25,26,27,28], #20 [6,8,9,20,21,23], [6,8,9,11,12,13,14,15,16,17,18,20,21,23], [1,2,3,4,5,6,8,9,11,12,13,14,15,16,17,18,20,21,23,24,25,26,27,28], [1,14,15,28], [1,3,4,5,6,8,9,10,11,12,14,15,17,18,19,20,21,23,24,25,26,28], #25 [1,3,4,5,6,8,9,10,11,12,14,15,17,18,19,20,21,23,24,25,26,28], [1,5,6,23,24,28], [1,2,3,5,6,8,9,11,12,13,14,15,16,17,18,20,21,23,24,26,27,28], [1,2,3,5,6,8,9,11,12,13,14,15,16,17,18,20,21,23,24,26,27,28], [1,8,9,14,15,20,21,28], # 30 [1,3,4,5,6,7,8,9,10,11,12,14,15,17,18,19,20,21,22,23,24,25,26,28], [1,3,4,5,6,7,8,9,10,11,12,14,15,17,18,19,20,21,22,23,24,25,26,28], [1,28], [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28], ] #builds the boxes bx=0 by=-16 for row in boundaries: #y co ordinate by=by+16 for n in row: #x co ordinate n=n-1 bx=n*16 box = boxcollisions(bx, by) box.draw(screen) #moves pacman sprite.movement() sprite.draw(screen) #tests for collision print(pygame.sprite.collide_rect(sprite, box)) pygame.display.flip() clock.tick(60)
1 - You need update the top and left position at moviment method. look: # move pacman def movement(self): pressed= pygame.key.get_pressed() if pressed[pygame.K_UP]: self.y -= 2 if pressed[pygame.K_DOWN]: self.y += 2 if pressed[pygame.K_LEFT]: self.x -= 2 if pressed[pygame.K_RIGHT]: self.x += 2 self.rect.left = self.x self.rect.top = self.y 2 - You have to verificate the collision into loop, for verification with all boxes for row in boundaries: #y co ordinate by=by+16 for n in row: #x co ordinate n=n-1 bx=n*16 box = boxcollisions(bx, by) box_list.append(box) box.draw(screen) if pygame.sprite.collide_rect(sprite, box): print("collided")
Use rect.collidelist to test if pacman is colliding with a wall sprites in your wall sprites list. It will return -1 as long as no collision is detected