ok so I created a game with python its like 2d ping pong, the problem comes when I made that if the ball_y == racket_y it doesnt apply to the while racket it only apply on the Lowest cord of the racket and not on the whole racket
This is because the y value of a rectangle in pygame is determined by a point. Usually it's the top left, but I guess in your case the racket_y is it's bottom left. A better way to do the collisions is to use the racket itself and the colliderect function, which checks for collisions between the entirety of the ball and the entirety of the racket. Note, to use it you have to call the function on the object's rect you want to start at, and in parenthesis you state the rectangle of the other object. Then you invert the direction of the ball.
Related
Currently, the turtle and the enemy need to have the same coordinates and are limited to only one coordinate.
I want to make a round hitbox for both the turtle and the enemy that restarts the window when they touch.
I am new to python, so haven't really tried many different methods (as I do not know them) but I had two variables, one was the coordinates of the enemy, while the other was the coordinates of the turtle, they changed as they moved, it seems that the coordinates need to be exactly equal to each other so it doesn't really work.
There are no formal hitboxes in the turtle module, but you can check an area around the turtle:
if abs(turtle.xcor() - enemy.xcor()) < 5 and abs(turtle.ycor() - enemy.ycor()) < 5:
take_damage()
would check to see if the enemy turtle is within a square with sides length 10 around the player turtle before damaging.
You can also check in a radius (see turtle.distance) or any other shape that pleases you.
Otherwise, there is no built-in hitbox with the turtle module. If you explore the docs, which I implore you do, you won't find a hitbox class or anything similar.
I'm making a game with Pygame, and now I stuck on how to process collision between player and wall. This is 2D RPG with cells, where some of them are walls. You look on world from top, like in Pacman.
So, I know that i can get list of collisions by pygame.spritecollide() and it will return me list of objects that player collides. I can get "collide rectangle" by player.rect.clip(wall.rect), but how I can get player back from the wall?
So, I had many ideas. The first was push player back in opposite direction, but if player goes, as example, both right and bottom directions and collide with vertical wall right of itself, player stucks, because it is needed to push only left, but not up.
The second idea was implement diagonally moving like one left and one bottom. But in this way we don't now, how move first: left or bottom, and order becomes the most important factor.
So, I don't know what algorithm I should use.
If you know the location of the centre of the cell and the location of the player you can calculate the x distance and the y distance from the wall at that point in time. Would it be possible at that point to take the absolute value of each distance and then take the largest value as the direction to push the player in.
e.g. The player collides with the right of the wall so the distance from the centre of the wall in the y direction should be less than the distance in x.
Therefore you know that the player collided with the left or the right of the wall and not the top, this means the push should be to the right or the left.
If the player's movement is stored as in the form [x, y] then knowing whether to push left or right isn't important since flipping the direction of movement in the x axis gives the correct result.
The push should therefore be in the x direction in this example
e.g. player.vel_x = -player.vel_x.
This would leave the movement in the y axis unchanged so hopefully wouldn't result in the problem you mentioned.
Does that help?
So i started some kinda big pygame project, everything went more or less well.
But now i'm really stuck at how to detect the directions of collisions.
So i got my character (2d sidescroller), and a sprite group for the obstacles which are by now all rects. Now however collision detection works fine, but is, and if it is then how, it possible to detect on which side of the obstacle rects the character rect collides with it?
Addition in case someone stumbles upon this question: The janky solution I ended up implementing used a "scaffolding" of four (invisible) lines per obstacle, one for each side. Once a collision with a specific obstacle was detected I looked up the four lines around the colliding rectangle in a dict and then went to check which of these lines was currently colliding with the player sprite. It kind of worked but the whole project was a mess anyway.
There are many 2D physics libraries that including collision detection and usually a large project like you said would require other physics like constraints, ray casting and bodies. A great library for python is pyBox2D and has good documentation on their github. pyBox2D will also fully handle collisions for you but you can also setup custom collision handlers.
For you question you ask how to check which position a rect collides with, you can do this using the pygame.Rect variables that are given like so
import pygame
def determineSide(rect1, rect2):
if rect1.midtop[1] > rect2.midtop[1]:
return "top"
elif rect1.midleft[0] > rect2.midleft[0]:
return "left"
elif rect1.midright[0] < rect2.midright[0]:
return "right"
else:
return "bottom"
rect1 = pygame.Rect(100, 100, 20, 20)
rect2 = pygame.Rect(100, 90, 20, 20)
print(determineSide(rect1, rect2))
Note this does not check for collision but simply checks where rect2 is relative to rect1.
Maybe you can check which one or two of the four corners on one Rect are inside the other. There is one problem, though - if the Rects are touching by the corners, it's up to the rest of the program what to do then. I haven't written a code snippet for this myself, but I'm working on a platformer as well and plan to create one.
I am trying to implement a Mario type plat-former in pyGame. I have Collision detection working with Polygons no problem. I am curious how I can get the player to be able to jump through the floor above him, which is a polygon floating in air.
What is the theory on how to handle that?
you could make it so that when your character hits a block, they move up at the current speed until they are no longer colliding with the polygon. That way, when you hit the ground from above,you don't go downward through it, but when you hit the bottom, you do. I would recommend a while loop set to the collide function.
Me and my friend are currently trying to make a game. In this game we wish to have nice collision detection. But we cannot seem to find the way to update the masks in the definiton while loop. :S We have tested it alot of times, with different values and even some really unlogical stuff.
Each time we move the player, the game crashes when it collides with the mask. Its like the loop goes on forever, even though the player and the bush should be going away from eachother when we move the mask and the background.
def check_collision():
while pygame.sprite.collide_mask(player, rock):
bg.x -= 1 #the x-value of the background
rock.x -=1 #the x-value of the object
This is just collision when going left using the button "a".
We also move the background and all the sprites instead of the player.
We need to use masks.
We know that it checks the collision, but the mask wont update after bg.x and rock.x are changed.
We assume that this is because the images aren't moved on the screen. And therefore we have tried putting a blit inside the while loop. It still would not work.
Thank you for helping, and a final question, is there any way to manually move a mask/object?
First of all, collision detection using masks is very time-intensive. Whether or not your game has entered an infinite loop, the processing requirements of a bitmask-bitmask overlap check will make your game run far too slowly.
A simple optimization exists, however:
Any object which is able to collide with things must have some maximum size -- that is, you can find a rectangle which will always contain your player, and your boulder can fit inside another. Therefore, if your player's box doesn't collide with the boulder's box, they can't possibly overlap. Since you insist on collision masking, (which can add some realism to any pixelart game), you can compute the per-pixel collision whenever (and only whenever) the bounding boxes collide.
Now, on to your coding style: >:O
It is never a good idea to put a potentially infinite loop within a function which should ideally compute an instant collision check. In the best-case scenario (which is certainly achievable), you would have one function to check whether two objects collide, and tell you some more useful information (the position of one relative to the other, etcetera); while a separate method of every moving object would fix the collisions.
This would translate to something like:
class CollidingObject:
#This class controls an object which can move and fix collisions
def __init__(self):
self.x = 0 #add relevant initialization code here
self.y = 0
self.xVel = 0 # X and Y velocity (for movement)
self.yVel = 0
self.xSize = 0 # the width of the object in pixels
self.ySize = 0 # the height of the object in pixels
def iscolliding(self, other):
# using x and y as the center of the object,
# this returns an empty tuple if they don't collide
if ((self.xSize + other.xSize) / 2 <= abs(self.x - other.x)) and
((self.ySize + other.ySize) / 2 <= abs(self.y - other.y)): return ()
"""
use pygame collidemask here to compute whether they collide.
if they do, return a vector of 'other's' position relative to self.
(this can be used to decide how to separate the objects)
"""
def restitute(self, overlaps_with, distances):
"""
Given some objects which overlap, and a list of 2D vectors of their
relative distances, this separates them however much you like.
"""
pass
As to where your colision checking is done, that depends upon your implementation of object management basics. I will heretofore assume that all of your in-game objects are contained within an iterable; and that on every frame you iterate through your objects, once to render, once to move them -- a structure something like this:
while NOT_QUIT:
for object in objects:
object.draw_to_screen()
object.move() # moves the object -- collisions, etc in here
event_handling_stuff() # handles events
In this case, every object can compute collision checking for anything which follows it in objects. In doing so, each object can collect how far it has to move from each. Afterwards, each object can move to be as far from each collider as possible.
In a few games I've written, I'd make objects move farther apart the more overlapped they are, giving collisions an elastic quality which makes even very rough restitution algorithms look very sexy. Generally, you can tinker with constants once you have a working check going and that would be the least of your worries.
Hopefully this will have helped you two a little (I realize now I went off a bit on a tangent, but you were asking about how to do the wrong things more efficiently :P).
tl;dr: Don't try to fix collisions within your collision check function. Instead, separate it into one which finds all collisions to other objects, and another which fixes all collisions for an object at the same time.
Add other questions and I'll update (:.
UPDATE 1
Expanding here on the "vector of other to self" bit (which was explained a tad crudely:/)
Generally when two objects collide in real life, they bounce back somewhat in the direction they came from (when you drop a rubber bouncy ball on the floor, it bounces back from whence it came -- it doesn't just phaze through the floor). In most programming applications, you'd want to make bouncy balls (and other colliding things) behave in the same way (well, sometimes you might want the ball to phaze though the floor, but that's even easier than bouncing IMHO :P).
To know which way an object must bounce back, you have to know the direction from which it came. More strictly, you have to know the angle at which it collided. This is very easily found if you compare the distance and direction between the centers of each object during the collision. This will provide a pretty accurate representation of two objects bouncing, if the centers you are using are close enough to their centers of mass (in most games the middle of an object is an easy and good approximation).
So, since we don't need to worry about center of mass and all that, we just measure the vector distance between object positions:
#Continuing the previous example, we put some code like this in 'iscolliding' :)
if they collide (pygame mask stuff) :
x_distance = self.x - other.x
y_distance = self.y - other.y
return (x_distance, y_distance)
This code can give you the line along which each object should move to resolve the collision as fast as possible. The rest is a matter of accelerating each object along this line, making sure they don't go closer together (pay attention to signs), and tweaking constants to create a realistic effect.