Reputation: 89
I've been learning how to use pygame and came across a tutorial for making your character jump. The code isn't exactly the same, but I don't see why it shouldn't work.
I'm wondering why he would make the jump count False
initially if he was going to ask:
if not (p1jump):
if keys[pygame.K_SPACE]:
p1jump = True
This is confusing to me because p1jump
is false initially. So you're basically asking: if p1jump is true, and SPACE is pressed, then set p1jump to true.
Here's the whole class just in case:
class Player1():
def __init__(self,x,y):
self.x = x
self.y = y
self.height = 25
self.width = 25
self.speed = 5
def draw(self,r,g,b):
pygame.draw.rect(win,(r,g,b),(self.x,self.y, self.width ,self.height))
def movement(self):
p1jump = False
jumpcount = False
keys = pygame.key.get_pressed()
if keys[pygame.K_a] and self.x > self.speed:
self.x -= self.speed
elif keys[pygame.K_d] and self.x < (w - self.width):
self.x += self.speed
if not(p1jump):
if keys[pygame.K_SPACE]:
p1jump = True
else:
if jumpcount >= -10:
self.y -= (jumpcount **2) *0.5
jumpcount = 1
else:
p1jump = False
jumpcount = 10
Also, if you guys have any better ways to code a jump please let me know! Thank you!
Upvotes: 0
Views: 60
Reputation: 9746
Your first code snippet is correct. However, in the method movement
you're setting p1jump
to False
every time it's called. I'm guessing you want it to keep being True
until the player lands. So make that variable an attribute instead.
class Player:
def __init__(self,x,y):
# ... stuff
self.jump = False
def movement(self):
# ... stuff
if not self.jump and keys[pygame.K_SPACE]:
self.jump = True
else:
if jumpcount >= -10:
self.y -= (jumpcount **2) *0.5
jumpcount = 1
else:
self.jump = False
jumpcount = 10
Upvotes: 1
Reputation: 331
So you're basically asking: if p1jump is true, and SPACE is pressed, then set p1jump to true.
Not exactly, not (p1jump):
is True
if p1jump is False
. not
is an inverse operator in Python.
if not (p1jump)
could be rewritten as if p1jump == False
if that's clearer to you.
I hope that helps.
Upvotes: 0