저는 파이 게임 게임에서 같은 결과를 보았습니다. 당신이하고 싶은 것은 모든 물체가 사용할 이동을위한 함수를 만드는 것입니다. 모든 것을 의미하는 렌더링 업데이트 그룹에서 어떤 스프라이트를 통과하는 것은 불가능합니다. 스프라이트가 모든 것에 포함되지 않으면 충돌하지 않습니다. 여기에 함수가 있습니다. 이것은 충돌에 대해 일정량의 저항을 만듭니다. 기본적으로 물체를 밀면 일정량 뒤로 밀려납니다. 이동 기능을 호출하지 않는 객체는 푸시 되어도 움직이지 않으므로 처음부터 움직일 수있는 객체 만 밀어 넣을 수 있습니다. 벽과 같은 물건은 밀어 넣을 때 보드 위로 미끄러지지 않습니다.
def moveRelative(self,other,speed): #This function is a function the one you need uses, which you may find useful. It is designed to move towards or a way from another sprite. Other is the other sprite, speed is an integer, where a negative value specifies moving away from the sprite, which is how many pixels it will move away from the target. This returns coordinates for the move_ip function to move to or away from the sprite, as a tuple
dx = other.rect.x - self.rect.x
dy = other.rect.y - self.rect.y
if abs(dx) > abs(dy):
# other is farther away in x than in y
if dx > 0:
return (+speed,0)
else:
return (-speed,0)
else:
if dy > 0:
return (0,+speed)
else:
return (0,-speed)
def move(self,dx,dy):
screen.fill((COLOR),self.rect) #covers over the sprite's rectangle with the background color, a constant in the program
collisions = pygame.sprite.spritecollide(self, everything, False)
for other in collisions:
if other != self:
(awayDx,awayDy) = self.moveRelative(other,-1) #moves away from the object it is colliding with
dx = dx + 9*(awayDx) #the number 9 here represents the object's resistance. When you push on an object, it will push with a force of nine back. If you make it too low, players can walk right through other objects. If you make it too high, players will bounce back from other objects violently upon contact. In this, if a player moves in a direction faster than a speed of nine, they will push through the other object (or simply push the other object back if they are also in motion)
dy = dy + 9*(awayDy)
self.rect.move_ip(dx,dy) #this finally implements the movement, with the new calculations being used
코드 종류가 다양하므로 원하는대로 변경할 수 있지만 꽤 좋은 방법입니다. 바운스 백 기능을 제거하려면 객체 방향으로의 움직임을 0으로 설정하고 움직임을 없애기 만하면됩니다. 그러나 바운스 백 기능이 내 게임에 유용하고 더 정확하다는 것을 알았습니다.
전체 코드를 표시 할 수 있습니까? 오타 일 수 있습니다. – Patashu
전체 이동 코드 추가 : –
한 가지 생각은 위치를 지정하기 위해 부동 소수점을 사용하는 경우 반올림 오류는 사용자가 밀어 넣은만큼 밀어 넣지 않는 것을 의미 할 수 있습니다. 디버거를 사용하거나 문을 인쇄하려고 했습니까? 또는 시간에 따른 위치 값을 추적하기위한 로깅? – Patashu