Accompanying video Tutorial

Accompanying video Tutorial

Project code

Project code

The final result

walking

constants.py

STAND = 'standing'
WALK = 'walk'

SMALL_ACCEL = .2
SMALL_TURNAROUND = .35
Copy the code

The Mary class constructor is modified as follows:

Mary class added and modified

def update(self, keys): self.handle_state(keys) self.update_position() self.animation() def update_position(self): self.rect.x += self.x_vel self.rect.y += self.y_vel def handle_state(self, keys): if self.state == c.STAND: self.standing(keys) elif self.state == c.WALK: self.walking(keys) def animation(self): if self.facing_right: self.image = self.right_frames[self.frame_index] else: self.image = self.left_frames[self.frame_index] def load_from_sheet(self): self.right_frames.append( self.get_image(178, 32, 12, 16)) # right self.right_frames.append( self.get_image(80, 32, 15, 16)) # right walking 1 self.right_frames.append( self.get_image(99, 32, 15, 16)) # right walking 2 self.right_frames.append( self.get_image(114, 32, 15, 16)) # right walking 3 self.right_frames.append( self.get_image(144, 32, 16, 16)) # right jump self.right_frames.append( self.get_image(130, 32, 14, 16)) # right skid # The left image frames are numbered the same as the right # frames but are simply reversed. for frame  in self.right_frames: new_image = pg.transform.flip(frame, True, False) self.left_frames.append(new_image)Copy the code

New Mary class

def standing(self, keys): self.frame_index = 0 self.x_vel = 0 self.y_vel = 0 if keys[pg.K_LEFT]: self.facing_right = False self.state = c.WALK elif keys[pg.K_RIGHT]: self.facing_right = True self.state = c.WALK else: self.state = c.STAND def walking(self, keys): if self.frame_index == 0: self.frame_index += 1 else: if self.frame_index < 3: self.frame_index += 1 else: self.frame_index = 1 if keys[pg.K_LEFT]: Self.facing_right = False self.x_accel = c.smal_accel # The left velocity is negative, if the minimum negative velocity is not reached, continue to the left # e.g. -3 > -4, X_vel > (self.max_vel * -1): self.x_vel -= self.accel elif keys[pg.k_right]: self.facing_right = True self.x_accel = c.SMALL_ACCEL if self.x_vel < self.max_x_vel: self.x_vel += self.x_accelCopy the code

Don’t shake

Can stop

Turn and acceleration