1

I've recently start using classes in Python (I'm 1000% a rookie) and so far I find it much easier to work with. However, while developing a mini game for my project I've come across the issue of player input. What I have tried should theoretically work, but like I said I am very new to this.

import pygame as pg
from settings import *
vec = pg.math.Vector2

class Player(pg.sprite.Sprite):
    def __init__(self):
        pg.sprite.Sprite.__init__(self)
        self.image = pg.Surface((30,40))
        self.image.fill(GREEN)
        self.rect = self.image.get_rect()
        self.rect.center = (WIDTH / 2, HEIGHT / 2)
        self.pos = vec(WIDTH / 2, HEIGHT / 2)
        self.vec = vec(0,0)
        self.acc = vec(0,0)

    def update(self):
        self.acc = vec(0,0)
        keys = pg.key.get_pressed()
        if keys[pg.K_LEFT]:
            self.acc.x = -PLAYER_ACC
        if keys[pg.K_RIGHT]:
            self.acc.x = PLAYER_ACC

        self.acc += self.vel * PLAYER_FRICTION
        self.vel += self.acc
        self.pos += self.vel + (0.5 * self.acc)
        if self.pos.x > WIDTH:
            self.pos.x = 0
        if self.pos.x < 0:
            self.pos.x = WIDTH

        self.rect.center = self.pos

So far, this draws the rectangle at the desired location, and there are no errors showing on shell, so I know I haven't mistyped anything.

Have I done something wrong? Or is it my logic thats wrong?

(P.S: this is part of a larger program, just split off into multiple files such as a main file with the game class in it - hence the 'from settings.)

EDIT: apologies, the issue is that the sprite is drawn properly but when I press either the left or right arrow key, the sprite isn't moving as it should

  • @roganjosh, apologies, edited – Brandon Robinson Feb 08 '18 at 17:30
  • 1
    Please provide a [minimal, complete and verfiable example](https://stackoverflow.com/help/mcve). Some important constants are missing here, the `PLAYER_ACC` and `PLAYER_FRICTION`. The code that you've posted works correctly (with acc = 0.5 and friction = -0.12), so the error must be elsewhere or something is wrong with your constants. – skrx Feb 09 '18 at 06:57
  • 1
    I think the error is that you never call `update` on the sprite. Because if you would, you would get an attribute error because `self.vel` is accessed before it is defined. If you use sprites, make sure to put them in a group and call `draw` and `update` on that group. – sloth Feb 09 '18 at 07:25
  • You should learn to debug such cases, using a debugger or even using print statements to print out the state of your sprite so you can see what's going on, like: is this method called at all? are these values changed the way I expect? – sloth Feb 09 '18 at 07:26

0 Answers0