Nischal Keshav
Nischal Keshav

Reputation: 41

Why is my KINEMATIC body not moving even though I set the velocity?

I am pretty new to Pymunk so I am having some trouble with kinematic bodies. In this program, I set the velocity of the shape, but it still doesn't move.

Full code below:

import pygame
import pymunk
import time
pygame.init()

Screen = pygame.display.set_mode((800,800))
BG_Color = (255,255,210)
Space = pymunk.Space()


class Player:
    def __init__(self):
        self.x = 400
        self.y = 60


        self.body = pymunk.Body(1,1666, pymunk.Body.KINEMATIC)
        self.shape = pymunk.Segment(self.body, (self.x,self.y), (self.x+32, self.y), 20)
        self.shape.position= self.x,self.y
        self.shape.body.velocity = (10, 10)

 def move(self):
        self.pos = self.shape.body.position
        self.x = self.pos[0]
        self.y = self.pos[1]
        print(self.x)


Player = Player()
Cont = True 

while Cont:
    #Screen.fill(BG_Color)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            Cont = False

    Player.move()
    Space.step(120)
    pygame.display.update()
    time.sleep(1/120)

Do you have any idea how this could be happening?

I Just want to move this object diagonally by the way.

Upvotes: 1

Views: 203

Answers (1)

Rabbid76
Rabbid76

Reputation: 210968

You need to add the body and the shape to the space

space.add(player.body, player.shape)

And you need to draw the scene:

screen = pygame.display.set_mode((800,800))
draw_options = pymunk.pygame_util.DrawOptions(screen)
while cont:
    # [...]

    screen.fill(BG_Color)
    space.debug_draw(draw_options)
    pygame.display.update()

Complete example:

import pygame
import pymunk
import pymunk.pygame_util
import time
pygame.init()

screen = pygame.display.set_mode((800,800))
draw_options = pymunk.pygame_util.DrawOptions(screen)
BG_Color = (255,255,210)
space = pymunk.Space()

class Player:
    def __init__(self):
        self.x = 10
        self.y = 10
        self.body = pymunk.Body(1,1666, pymunk.Body.KINEMATIC)
        self.shape = pymunk.Segment(self.body, (self.x,self.y), (self.x+32, self.y), 20)
        self.shape.position= self.x,self.y
        self.shape.body.velocity = (10, 10)

    def move(self):
        self.pos = self.shape.body.position
        self.x = self.pos[0]
        self.y = self.pos[1]
        print(self.x)

player = Player()
cont = True 
space.add(player.body, player.shape)

while cont:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            cont = False

    player.move()
    space.step(1/120)
    
    screen.fill(BG_Color)
    space.debug_draw(draw_options)
    pygame.display.update()
    time.sleep(1/120)

Upvotes: 3

Related Questions