1

I'm creating a game in PyGame where I need to pick up a plate and move it around the kitchen. so far I have managed to have the player collide and interact with the object but have not been able to pick up and move the object around the screen. I've been stuck on this issue for weeks and any help would be massively appreciated.

def new(self):
  self.plate = pg.sprite.Group()
  for tile_object in self.map.tmxdata.objects:
    if tile_object.name == 'plate':
            self.plate.x = tile_object.x
            self.plate.y = tile_object.y
            Plate(self, self.plate.x, self.plate.y)
      touch=False
      if (tx-32)<= x and (tx+32) >= x and (ty-64)<= y and (ty+64) >= y:
          touch = True
      elif (ty-32)<= y and (ty+32) >= y and (tx-64)<= x and (tx+64) >= x:
          touch = True
      return(touch)
 
def update(self):
      self.all_sprites.update()
      x = self.player.pos[0]
      y = self.player.pos[1]
      holding = 0
      keys_pressed = self.get_pg_events()```

      touch = self.grid_location(self.player.pos[0] ,self.player.pos[1] ,self.plate.x, self.plate.y)
      if touch == True:
          self.space_bar_plate.reposition(self.player.pos[0], self.player.pos[1]+64)
          keys = pg.key.get_pressed()
          if keys[pg.K_SPACE]:
              now = pg.time.get_ticks()
              if now - self.player.last_action > ACTION_RATE:
                  self.player.last_action = now
                  self.plate.x = math.cos(self.player.rot*math.pi/180)*80+self.player.pos[0]
                  self.plate.y = math.sin(self.player.rot*math.pi/180)*80+self.player.pos[1]
                  self.plate = Plate(self, self.plate.x , self.plate.y)
     else:
         self.space_bar_plate.reposition(-32, 0)```

in my sprites file

class Plate(pg.sprite.Sprite):
  def __init__(self, game, x, y):
      self.groups = game.all_sprites, game.plate
      pg.sprite.Sprite.__init__(self, self.groups)
      self.game = game
      self.image = game.plate_img
      self.rect = self.image.get_rect()
      self.pos = (x, y)
      self.rect.center = self.pos

  def reposition(self, x, y):
      self.pos = (x, y)
      self.rect.center = self.pos

2 Answers 2

1

Here's a simple example of how to do something like that. Use W,A,S,D to move and SPACE to pick up and drop the black box.

import pygame

RESOLUTION = 800, 600
TILESIZE = 32
PLAYER_SPEED = 200
FPS = 60

class Player(pygame.sprite.Sprite):
    def __init__(self, pos, *grps):
        super().__init__(*grps)
        self.image = pygame.Surface((TILESIZE, TILESIZE))
        self.image.fill('dodgerblue')
        self.rect = self.image.get_rect(center=pos)
        self.pos = pygame.Vector2(pos)
        self.movement = pygame.Vector2()
        self.item = None

    def update(self, dt, events):
        pressed = pygame.key.get_pressed()
        self.movement.x, self.movement.y = 0, 0
        if pressed[pygame.K_w]: self.movement.y = -1
        if pressed[pygame.K_a]: self.movement.x = -1
        if pressed[pygame.K_s]: self.movement.y =  1
        if pressed[pygame.K_d]: self.movement.x =  1
        if self.movement.length() > 0:
            self.movement.normalize_ip()
        self.pos += self.movement * dt * PLAYER_SPEED
        self.rect.center = self.pos

        if self.item:
            self.item.pos += self.movement * dt * PLAYER_SPEED
            self.item.rect.center = self.item.pos

        for e in events:
            if e.type == pygame.KEYDOWN and e.key == pygame.K_SPACE:
                self.pick_up() if not self.item else self.drop()

    def pick_up(self):
        collisions = pygame.sprite.spritecollide(self, self.groups()[0], False)
        items = list(s for s in collisions if hasattr(s, 'can_be_picked_up') and s.can_be_picked_up)
        if items:
            self.item = items[0]

    def drop(self):
        self.item = None

class Plate(pygame.sprite.Sprite):
    def __init__(self, pos, *grps):
        super().__init__(*grps)
        self.image = pygame.Surface((TILESIZE, TILESIZE))
        self.image.fill('black')
        self.rect = self.image.get_rect(center=pos)
        self.pos = pygame.Vector2(pos)
        self.can_be_picked_up = True

def main():
    pygame.init()
    screen = pygame.display.set_mode(RESOLUTION)
    dt, clock = 0, pygame.time.Clock()
    sprites = pygame.sprite.Group()
    Player((400, 300), sprites)
    Plate((200, 200), sprites)
    while True:
        events = pygame.event.get()
        for e in events:
            if e.type == pygame.QUIT:
                return
        screen.fill('grey')
        sprites.update(dt, events)
        sprites.draw(screen)
        pygame.display.flip()
        dt = clock.tick(FPS) / 1000

if __name__ == "__main__":
    main()

enter image description here

As you can see, in the update function of the Player we check if space was pressed. Then we check if we're already holding an item.

If yes, we drop it.

If not, we check all sprites that we currently collide with and take that first that has can_be_picked_up set to True (you don't have to do this this way but why not) and pick it up.

Picking it up just means setting it to self.item and then update its position in the player's update method, too.

Of course, there are multiple ways to do something like this; but I think this quite similar to what you tried to do in your code.

Sign up to request clarification or add additional context in comments.

Comments

0

First you track if a click is made and change a variable to True:

if event.type == pygame.MOUSEBUTTONDOWN:
    clicked = True

If you release the mouse you reset this variable:

elif event.type == pygame.MOUSEBUTTONUP:
    clicked = False

Then again in your pygame loop you track the mouse position by:

elif event.type == pygame.MOUSEMOTION:
    if clicked:
        x, y = pygame.mouse.get_pos()[0], pygame.mouse.get_pos()[1]

Then when you blit the image you do it with these x and y values.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.