Pymunk 身体在不相互接触的情况下发生碰撞

Pymunk bodies colliding without touching each other

为什么即使在位置和 body 形状设置正确后,pymunk 中的物体仍会继续碰撞而不会实际相互接触?

你会从我下面的代码中看到,小鸟一直在与球碰撞,但实际上并没有接触到球。

import pygame, pymunk
pygame.init()

WIDTH, HEIGHT = 900, 500
win = pygame.display.set_mode((WIDTH,HEIGHT))
pygame.display.set_caption("Flappy OBJ")

color = (255,255,255)

win.fill(color)

fps = 120

fb_img = pygame.image.load("images/flappy-bird.png")#.convert()
fb_img = pygame.transform.rotate(pygame.transform.scale(fb_img, (30,20)), 0)
ball_img = pygame.image.load("images/ball.png")#.convert()
ball_img = pygame.transform.rotate(pygame.transform.scale(ball_img, (60,60)), 0)

def bird_body():
    body = pymunk.Body(1, 100, body_type=pymunk.Body.DYNAMIC)
    body.position = (50, 0)
    shape = pymunk.Poly.create_box(body, (30,20))
    space.add(body, shape)
    return shape

def ball_body():
    body = pymunk.Body(1, 100, body_type = pymunk.Body.KINEMATIC)
    body.position = (500, 300)
    body.velocity = (-25,0)
    shape = pymunk.Circle(body, 60)
    shape.color = (0,255,255, 128)
    space.add(body, shape)
    return shape

space = pymunk.Space()

space.gravity = (0, 20)
fb_body = bird_body()
b_body = ball_body()


def draw_window():
    global scroll
    win.fill(color)

    space.step(0.03)
    
    win.blit(ball_img, (b_body.body.position.x, b_body.body.position.y))
    win.blit(fb_img, (fb_body.body.position.x, fb_body.body.position.y))
    
    pygame.display.update()

def main():
    w_was_down = True

    clock = pygame.time.Clock()
    run = True
    while run:
        clock.tick(fps)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False

        keys_pressed = pygame.key.get_pressed()
        
        if keys_pressed[pygame.K_w]:
            if not w_was_down:
                fb_body.body.apply_impulse_at_local_point((0,-50))
                w_was_down = True
        else:
            w_was_down = False

        draw_window()

    pygame.quit()
main()

点击 w 将小鸟向上移动。更详细一些更详细一些更详细

pymunk.Circle的第二个参数是半径,不是直径:

shape = pymunk.Circle(body, 60)

shape = pymunk.Circle(body, 30)

pymuk对象的位置就是对象的中心:

win.blit(ball_img, (b_body.body.position.x, b_body.body.position.y))
win.blit(fb_img, (fb_body.body.position.x, fb_body.body.position.y))

win.blit(ball_img, (b_body.body.position.x-30, b_body.body.position.y-30))
win.blit(fb_img, (fb_body.body.position.x-15, fb_body.body.position.y-10))