I'm making a 2D platformer game using Pygame, and I have made a code to detect if my character is on the floor or not. Below are the codes for the falling and the collision detection.
This is the collision code (In the Hitbox class):
def is_on_floor(self):
check_y = self.rect.y + self.rect.height
parent_y = self.rect.y - self.y_offset
collided = False
block_x, block_y,block_width,block_height = 0,0,0,0
points = [[self.rect.x, self.rect.y],
[self.rect.x + self.rect.width, self.rect.y],
[self.rect.x, self.rect.y + self.rect.height],
[self.rect.x + self.rect.width, self.rect.y + self.rect.y]]
for obj in world:
for point in points:
if obj.hitbox.rect.x <= point[0] <= obj.hitbox.rect.x + obj.hitbox.rect.width and\
obj.hitbox.rect.y <= point[1] <= obj.hitbox.rect.y + obj.hitbox.rect.height and\
collided == False:
block_x = obj.hitbox.rect.x
block_y = obj.hitbox.rect.y
block_width = obj.hitbox.rect.width
block_height = obj.hitbox.rect.height
collided = True
break
if collided:
self.rect.y = block_y - self.rect.height
parent_y = self.rect.y - self.y_offset
return parent_y, collided
And this is the falling code (In the Player class):
def fall (self):
self.y_speed += 0.4
self.y_pos += self.y_speed
self.hitbox.update(self.x_pos,self.y_pos)
floor_check, collided = self.hitbox.is_on_floor()
if collided:
self.y_pos = floor_check
self.can_jump = True
self.y_speed = 0
The problem is that my character just falls through the floor. But, the character does stand on a raised block that I added to the level for testing purposes. Does anyone know how I can fix it?
EDIT: For adding new blocks, I am creating a copy of the block object. I tried this:
obj = copy.copy(self)
obj.hitbox = copy.copy(self.hitbox)
world.append(obj)
But it seems that when I update the block (So that the hitbox moves to it's position), it updates one hitbox that appears to be shared between the block objects. What I don't understand is that I used copy.copy(self.hitbox)
to copy the hitbox, but for some reason this doesn't seem to be working.