I'm sorry if this question has already been asked before but I've checked everywhere and I can't find the answer.
How do you do top down movement in pygame?
This would be easy if I was just using rectangles but I'm going to be using individual character sprites (Ex. If I press d to make player go right, it shows me the character sprite of him going right and moves the character right).
Example image of what I mean:
You draw a different sprite depending on which direction the character is going.
Assuming dx / dy are the character's velocity and x/y its location on screen,
up_sprite = pygame.image.load('up.png')
down_sprite = pygame.image.load('down.png')
left_sprite = pygame.image.load('left.png')
right_sprite = pygame.image.load('right.png')
sprite = down_sprite # to initialize things off with
def your_game_loop():
if dx > 0:
sprite = right_sprite
elif dx < 0:
sprite = left_sprite
elif dy > 0:
sprite = down_sprite
elif dy < 0:
sprite = up_sprite
sprite.blit(screen, (x, y))
Related
I've been trying to do horizontal and vertical collisions, and I'm having problems with horizontal. I've used collisioncheck as a method to verify how many tiles a player is touching, as that's the only difference I could think of for horizontal and vertical. But, my player never touches 2 tiles as the vertical collisions for some reason always comes first and instead of colliding with 2 tiles my player simply gets sent up.
collisioncheck=pygame.sprite.groupcollide(self.player,self.tiles,False,False)
for tile in self.tiles.sprites():
if player.rect.colliderect(tile.rect):
if player.direction.y>0:
player.rect.bottom=tile.rect.top
player.direction.y=0
elif player.direction.y<0:
player.rect.top=tile.rect.bottom
player.direction.y=0.1
You must handle horizontal and vertical movements and collisions separately:
Move the player in x-direction
Detect the collisions and limit the movement of the player in X-direction
Move the player in y-direction
Detect the collisions and limit the movement of the player in y-direction
You can try to separate only the collision detection and the limitation of the players position depending on the movement axis and not the movement itself, however this may not completely solve your problem. It will be a problem if you always fall down slightly, even if you are standing on a tile, so the horizontal collision detection will always detect a collision with the tiles you are standing on.
Your code should look something like this:
# do the horizontal movement here, something like:
# player.rect.x += player.direction.x
collide_x = False
collisioncheck=pygame.sprite.groupcollide(self.player,self.tiles,False,False)
for tile in self.tiles.sprites():
if player.rect.colliderect(tile.rect):
if player.direction.x > 0:
player.rect.right = tile.rect.left
collide_x = True
elif player.direction.x < 0:
player.rect.left = tile.rect.right
collide_x = True
if collide_x:
player.direction.x = 0
# do the vertical movement here, something like:
# player.rect.y += player.direction.y
collide_y = False
collisioncheck=pygame.sprite.groupcollide(self.player,self.tiles,False,False)
for tile in self.tiles.sprites():
if player.rect.colliderect(tile.rect):
if player.direction.y > 0:
player.rect.bottom = tile.rect.top
collide_y = True
elif player.direction.y <= 0:
player.rect.top = tile.rect.bottom
collide_y = True
if collide_y:
player.direction.y = 0
This question already has answers here:
Blitting images onto a tile that is part of a grid in pygame
(1 answer)
Plotting pieces on a checkerboard using pygame
(1 answer)
Closed 1 year ago.
For the game I am making at the moment, I have just added collision detection to it. I draw the tiles on the screen and have an array with values of each tile. I'm using a for loop for checking each tile in my array to see if my character will collide with it, and stopping the movement if it is.
This is part of the player update function:
for tile in world.tiles:
#check collision in x-axis
if tile[1].colliderect(self.rect.x + dx, self.rect.y, self.width, self.height):
dx = 0
#check collision in y-axis
if tile[1].colliderect(self.rect.x, self.rect.y + dy, self.width, self.height):
#below ground
if self.vel_y < 0:
dy = tile[1].bottom - self.rect.top
self.vel_y = 0
#above ground
elif self.vel_y >= 0:
dy = tile[1].top - self.rect.bottom
Do you know any ways of drawing objects to the screen without the player being stopped by them? Could I make another list and draw that to the screen? The only problems I have with that idea is about more lag being created.
Please tell me if you need me to show you more of the code and thanks for any help you can give me
I am trying to get a ball to bounce off of the walls of my bounds. Currently, my circle is supposed to hit the wall and then change velocities and move in the opposite direction but this is not happening. I would appreciate some help :) Thank you
from graphics import*
from random import*
from time import*
win = GraphWin('My Program', 600, 600)
win.setBackground('pink')
my_circle = Circle(Point(200,300),30)
my_circle.setFill('blue')
my_circle.setOutline('darkorchid1')
my_circle.draw(win)
key = win.checkKey()
while key == '':
vel_x = randint(-30,30)
vel_y = randint(-30,30)
my_circle.move(vel_x, vel_y)
sleep(0.1)
for bounce in range(600):
find_center = my_circle.getCenter()
center_x = find_center.getX()
center_y = find_center.getY()
if center_x == 600 or center_y == 600:
vel_x = -randint(30,-30)
vel_y = -randint(30,-30)
my_circle.move(vel_x, vel_y)
sleep(0.1)
key = win.checkKey()
Several things that may affect the problem.
You should set your velocities once, as you're doing in the first lines in the while loop. Whenever it bounces you should move in the opposite direction using vel_x = -vel_x and vel_y = -vel_y.
Right now you're updating both of velocities which might lead to some wierd bounces when only one of the centeres hits a wall.
It might be more logical to check wether the distance from the center to the wall is less than the radius of the circle. This will prevent the issue when the ball moves from x=599 to x=601 in one iteration, skipping the if statement. (This would also make it so that the circle bounces when its edge hits the wall instead of the center)
Currently you're only checking 2 walls, unless you meant to do this you should add the if statements for the other walls aswell.
Small other thing, the second time you draw the random velocities you draw from the range 30 to -30, which is invalid.
I am learning python using pygame and I am working on something that involves sprites and collisions. I've looked at some examples but I still don't quite understand it. What I am attempting to do is to be able to add sprites(a ball) when the user presses the "=" key and also be able to remove the last sprite added when pressing "-". I am not able to remove just the last one, I have only been able to remove all of them.
So far I have been able to add the balls to the window and have them bounce off the walls and one another(sort of). When 2 balls collide, they don't completely touch yet they bounce off. Sometimes the balls get stuck and won't move and sometimes the balls bounce off the frame which they aren't suppose to.
Its my first time working with sprite groups and would appreciate any help/guidance into making this work smoothly.Thanks.
The code:
ball.py
import pygame
from pygame.locals import *
class Ball(pygame.sprite.Sprite):
def __init__(self, x, y, vx, vy):
super().__init__();
self.image = pygame.image.load("ball.png").convert()
self.image.set_colorkey(pygame.Color(0, 0, 0))
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
self.vx = vx
self.vy = vy
def draw(self, SCREEN):
SCREEN.blit(self.image, (self.rect.x, self.rect.y))
def move(self, SCREEN, balls):
l_collide = self.rect.x + self.image.get_width() + self.vx > SCREEN.get_width()
r_collide = self.rect.x + self.vx < 0
t_collide = self.rect.y + self.vy < 0
b_collide = self.rect.y + self.image.get_height() + self.vy > SCREEN.get_height()
a = pygame.sprite.spritecollide(self, balls, False, False)
if len(a) > 1:
self.vx *= -1
self.vy *= -1
if l_collide or r_collide:
self.vx *= -1
if t_collide or b_collide:
self.vy *= -1
self.rect.x += self.vx
self.rect.y += self.vy
ball_animation.py
import pygame
import sys
import random
import math
from pygame.locals import *
from ball.ball import Ball
from random import randint
def ball_list(num):
ball_list = pygame.sprite.Group()
for x in range(num):
rand_x = random.randint(0,400)
rand_y = random.randint(0,400)
vx = 4
vy = 5
ball_list.add(Ball(rand_x, rand_y, vx, vy))
return ball_list
def main():
pygame.init()
FPS = 30
FPS_CLOCK = pygame.time.Clock()
# COLOR LIST
BLACK = pygame.Color(0, 0, 0)
# Code to create the initial window
window_size = (500, 500)
SCREEN = pygame.display.set_mode(window_size)
# set the title of the window
pygame.display.set_caption("Bouncing Ball Animation")
# change the initial background color to white
SCREEN.fill(BLACK)
balls = ball_list(0)
while True: # <--- main game loop
for event in pygame.event.get():
if event.type == QUIT: # QUIT event to exit the game
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key == K_EQUALS:
balls.add(Ball(randint(0,400),randint(0,400), 4,5))
if event.key == K_MINUS:
try:
balls.remove()
except IndexError:
print('There is no balls to take!')
SCREEN.fill(BLACK)
for x in balls:
x.move(SCREEN,balls)
x.draw(SCREEN)
pygame.display.update() # Update the display when all events have been processed
FPS_CLOCK.tick(FPS)
if __name__ == "__main__":
main()
Removing Sprites on Press
The problem is sprite.Group.remove(sprites) wants you to specify which sprites it should remove. sprites here should be a sprite/list of sprites that you want to remove from the group. This means to remove the last ball added on key press you need to keep a list of the ball sprites and pop() the most recently added item from it, and then use the result of the pop() as the sprite to remove from the group. sprite.Group has a .sprites() method which returns a list of all sprites in the group, in the order they were added. This list is generated from the group and is not actually an interface with it, so doing things to this list won't affect the group. We can still however use it to get the last added sprite. Here is what it looks like:
elif event.key == K_0:
try:
sprite_list = balls.sprites()
to_remove = sprite_list[-1] # Get last element of list
balls.remove(to_remove)
except IndexError:
print('There is no balls to take!')
Collisions
So this is a bit more involved and not so simple to fix in your code. To understand what the problem is, look at what your collision velocity adjustments are actually doing for the screen border case.
l_collide = self.rect.x + self.image.get_width() + self.vx > SCREEN.get_width()
r_collide = self.rect.x + self.vx < 0
t_collide = self.rect.y + self.vy < 0
b_collide = self.rect.y + self.image.get_height() + self.vy > SCREEN.get_height()
#################
if l_collide or r_collide:
self.vx *= -1
if t_collide or b_collide:
self.vy *= -1
Consider a single time-step in your code. We check to see if the sprite is sitting over the edge of the boundaries by any amount. If its hanging over, we reverse the velocity. There is a case where your edge checking will get you into trouble. If your self.vx is less than the difference between your current position X and the boundary of the x dimension, you will reverse your speed, travel self.vx back towards the boundary, but not make it past. In the next time-step, you will see that you are still over the boundary, and your program will again reverse self.vx, actually sending you away from the boundary. In this case you will bound back and forth each time-step by self.vx. Normally this wouldn't happen in your code, except for when you spawn a new ball sprite over the boundary further than your self.vx or self.vy for that ball. This can be remedied by making sure you don't spawn balls off the edges, or better yet, only reversing your velocity if you need to.
if (l_collide and self.vx>0) or (r_collide and self.vx<0):
self.vx *= -1
if (t_collide and self.vy<0) or (b_collide and self.vy>0):
self.vy *= -1
Notice here we only reverse the velocity if we are over the edge AND the velocity is headed deeper in that direction. Now for your sprites you have two options, just like with the boundaries:
Only initiate a new ball in empty space where it cannot collide.
Implement some way to calculate the correct velocity adjustment and only apply it if the velocity is headed in the opposite direction.
From what I read in the documentation, sprite.Group looks like it is meant for checking if sprites are overlapping, and not for physics simulation. I recommend doing some research on 2d physics simulation to get a nice conceptualization of what information you should want to communicate between objects. I'm sure there are some nice tutorials out there.
Finally, to address your other question about why they are colliding when they don't appear to be touching. sprite.spritecollide is returning which sprites have rectangles that intersect. If your ball.png is color keyed for transparency, this does not affect the rect of the sprite. Pygame appears to have functionality implemented designed to handle this problem in the collided keyword of sprite.spritecollide:
pygame.sprite.spritecollide()
Find sprites in a group that intersect another sprite.
spritecollide(sprite, group, dokill, collided = None) -> Sprite_list
The collided argument is a callback function used to calculate if two sprites >are colliding. it should take two sprites as values, and return a bool value >indicating if they are colliding. If collided is not passed, all sprites must >have a “rect” value, which is a rectangle of the sprite area, which will be >used to calculate the collision.
collided callables:
collide_rect
collide_rect_ratio
collide_circle
collide_circle_ratio
collide_mask
That's from the pygame documentation. The documentation for the collide_circle function states that your sprite should have a radius attribute, or else one will be calculated to fit the entire rectangle inside a circle. As such, in your Ball.__init__ function I would recommend adding:
self.radius = self.rect.width/2
This will make collide_circle use a radius that approximates your ball image, assuming it is centered and circular and occupies the entire image. Next, you must add the collision specification to your collision check by changing:
a = pygame.sprite.spritecollide(self, balls, False, False)
to
a = pygame.sprite.spritecollide(self, balls, False, pygame.sprite.collide_circle)
If you solve the problem of not spawning new ball objects inside each other, this should all work nicely. If you can't get them to spawn inside each other, think about a different data-structure or different way of collision checking to get the results you want. Best of luck!
I can see two questions in your text
You want to only remove one sprite, rather than all the sprites in the spritegroup
If you look at the pygame documentation, you can see that spritegroup.remove has an optional argument. You can remove a single sprite by putting your desired sprite as the argument, such as myspritegroup.remove(mysprite).
You have issues with the colliding
Your collision works for me as long as the balls don't spawn on top of each other on creation which you can simply check. Good luck :)
I'm making a basic pong game (paddle is a rectangle on the bottom of the screen and the ball drops from the top of the screen). I want the ball to bounce back up ONLY when it hits the paddle. So far, I've written code that will make the ball bounce off the top and bottom screen, but I'm having trouble with getting the ball to bounce off the paddle.
I have to modify the parameters that are passed to my test_collide_ball method. If it’s current x values are within the range of the paddle, then it bounces back up.
I've been trying to think of a solution for this, and what I'm thinking is that if the ball hits the paddle's y coordinate (the height), then it bounces back up. But it also has to be within the range of x coordinates that make up the paddle (so the width of the paddle).
But when I do this, the ball just gets stuck in place. Any feedback is appreciated! Thanks in advance.
Here is my code for the ball class/methods:
import pygame
class Ball:
def __init__(self, x, y, radius, color, dx, dy):
self.x = x
self.y = y
self.radius = radius
self.color = color
self.dx = dx
self.dy = dy
def draw_ball(self, screen):
pygame.draw.ellipse(screen, self.color,
pygame.Rect(self.x, self.y, self.radius, self.radius))
def update_ball(self):
self.x += self.dx
self.y += self.dy
def test_collide_top_ball(self, top_height):
if (self.y <= top_height):
self.dy *= -1
def test_collide_bottom_ball(self, paddle):
if (self.y == paddle.y) and (self.x >= paddle.x) and (self.x <= paddle.x + paddle.width):
self.dy *= -1
What appears to be happening is your ball enters the collision zone and reverses it's direction. The ball is still in the collision zone, however, and it reverses it's direction again.
What you should look into is a debounce check. Put simply, this is code that prevents something from happening twice or more times (de-bouncing it).
From your code example, the ball's momentum is reversed when it enters the paddle zone. What you might add is a boolean flag to see if you have already detected that the ball entered the zone. When it is first detected, set the flag to true. When the ball moves outside of the zone, set the flag back to false. Only reverse the ball's momentum if the flag is false.
So, (excusing my rusty Python)
def test_collide_bottom_ball(self, paddle):
if (self.y == paddle.y) and (self.x >= paddle.x) and (self.x <= paddle.x + paddle.width) and (!self.hitPaddle):
self.dy *= -1
self.hitPaddle = true
else
self.hitPaddle = false
And in your entity:
self.hitPaddle = false
Just like #MrDoomBringer is saying, you need to prevent it from getting stuck within the pad.
One easy method to solve that is to check whether self.dy is positive - the ball is moving downwards. This way you could also add the same "within" check for the Y-pos as you did with the X-pos. Otherwise, having a collision with an exact Y-coordinate is pretty hard unless you're using the right speed etc.
Another thing - if you have a ball, you most likely want to add it's size to the equation. Then you might want to use some more fancy collision-techniques, such as this: http://www.migapro.com/circle-and-rotated-rectangle-collision-detection/