저는 Pygame을 사용하여 2D 플랫폼 게임을 만들고 있으며, 캐릭터가 바닥에 있는지 여부를 감지하는 코드를 만들었습니다. 아래는 낙하 및 충돌 감지 코드입니다. Pygame hitbox 충돌 문제
이
합니다 (hitbox에서 클래스에서) 충돌 코드 :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
그리고 이것은 (Player 클래스에서) 떨어지는 코드 :
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
문제는 나의 캐릭터 단지 바닥을 빠져 나간다. 그러나 문자 은 테스트 목적으로 레벨에 추가 한 돌출 블록에으로 표시됩니다. 아무도 내가 그것을 고칠 수있는 방법을 알고 있습니까?
편집 : 새 블록을 추가하려면 블록 개체 복사본을 만듭니다. 나는이 시도 :
obj = copy.copy(self)
obj.hitbox = copy.copy(self.hitbox)
world.append(obj)
을하지만 (그것의 hitbox에서의 이동 위치가 있다고 그래서) 나는 블록을 업데이트 할 때,이 블록의 객체간에 공유 할 것으로 보인다 하나 hitbox에서를 갱신 것으로 보인다. 내가 이해할 수없는 것은 내가 hitbox를 복사하기 위해 copy.copy(self.hitbox)
을 사용했다는 것이지만, 어떤 이유로 이건 작동하지 않는 것 같습니다.
'rect.x + rect.width' 대신'rect.y + rect.height'와'rect.right' 대신'rect.bottom'을 사용할 수 있습니다 – furas
pygame은 두 rect- 'rect.colliderect (other_rect)'와 rect와 point' rect.collidepoint (other_rect.topleft)'사이를 가리 킵니다. 'rect' 속성은'topleft','topright' 등이 있습니다. – furas
참조 http://stackoverflow.com/a/20183823/1832058 – furas