pygame-KidsCanCode系列jumpy-part4-彈跳


終於要到彈跳環節了,向上彈跳其實很簡單,按下空格觸發時,只要把y軸速度給一個向上的速度即可。

Player類,新加一個jump()方法:

    def jump(self):
        self.vel.y = -25

調用該方法,會使方塊具有向上25px的速度,然后由於重力依然在起作用,所以二者結合,就會形成向上彈跳的效果。

然后在main.py中按空格鍵時,調用jump方法,為了更有趣味性,我們多加幾個檔板,而且為了簡化代碼,把檔板的位置及長寬參數,都定義在settings.py中

# game options

SIZE = WIDTH, HEIGHT = 320, 480
FPS = 60
DEBUG = False

TITLE = "Jumpy!"

# Player properties
PLAYER_ACC = 0.6
PLAYER_GRAVITY = 2
PLAYER_FRICTION = -0.06

# 檔板列表
PLATFORM_LIST = [(0, HEIGHT - 30, WIDTH, 30),
                 (WIDTH / 2 - 50, HEIGHT * 0.75, 100, 15),
                 (WIDTH * 0.12, HEIGHT * 0.5, 60, 15),
                 (WIDTH * 0.65, 200, 80, 10),
                 (WIDTH * 0.5, 100, 50, 10)]

# define color
BLACK = 0, 0, 0
WHITE = 255, 255, 255
RED = 255, 0, 0
GREEN = 0, 255, 0
BLUE = 0, 0, 255
YELLOW = 255, 255, 0

main.py內容如下:

from part_04.sprites import *
from part_04.settings import *


class Game:

    def __init__(self):
        pg.init()
        pg.mixer.init()
        self.screen = pg.display.set_mode(SIZE)
        pg.display.set_caption(TITLE)
        self.clock = pg.time.Clock()
        self.running = True
        self.playing = False

    def new(self):
        self.all_sprites = pg.sprite.Group()
        self.platforms = pg.sprite.Group()
        self.player = Player(self)
        self.all_sprites.add(self.player)

        # 多放幾塊檔板
        for plat in PLATFORM_LIST:
            p = Platform(*plat)
            self.all_sprites.add(p)
            self.platforms.add(p)

        self.run()

    def run(self):
        self.playing = True
        while self.playing:
            self.clock.tick(FPS)
            self.events()
            self.update()
            self.draw()

    def update(self):
        self.all_sprites.update()
        hits = pg.sprite.spritecollide(self.player, self.platforms, False)
        if hits:
            self.player.pos.y = hits[0].rect.top
            self.player.vel.y = 0

    def events(self):
        for event in pg.event.get():
            if event.type == pg.QUIT:
                if self.playing:
                    self.playing = False
                self.running = False
            if event.type == pg.KEYDOWN:
                if event.key == pg.K_SPACE:
                    # 按空格鍵時,向上跳
                    self.player.jump()

    def draw(self):
        self.screen.fill(BLACK)
        self.all_sprites.draw(self.screen)
        self.debug()
        pg.display.flip()

    def debug(self):
        if DEBUG:
            font = pg.font.SysFont('Menlo', 25, True)
            pos_txt = font.render(
                'Pos:(' + str(round(self.player.pos.x, 2)) + "," + str(round(self.player.pos.y, 2)) + ")", 1, GREEN)
            vel_txt = font.render(
                'Vel:(' + str(round(self.player.vel.x, 2)) + "," + str(round(self.player.vel.y, 2)) + ")", 1, GREEN)
            acc_txt = font.render(
                'Acc:(' + str(round(self.player.acc.x, 2)) + "," + str(round(self.player.acc.y, 2)) + ")", 1, GREEN)
            self.screen.blit(pos_txt, (20, 10))
            self.screen.blit(vel_txt, (20, 40))
            self.screen.blit(acc_txt, (20, 70))
            pg.draw.line(self.screen, WHITE, (0, HEIGHT / 2), (WIDTH, HEIGHT / 2), 1)
            pg.draw.line(self.screen, WHITE, (WIDTH / 2, 0), (WIDTH / 2, HEIGHT), 1)

    def show_start_screen(self):
        pass

    def show_go_screen(self):
        pass


g = Game()
g.show_start_screen()
while g.running:
    g.new()
    g.show_go_screen()

pg.quit()

效果如下:

基本的彈跳實現了,但是有2個明顯的問題:

1. 可以在空中,不借助任何檔板的情況下,連環跳,這不太合理,比較貼近現實的預期效果應該是,只在在檔板上,才允許起跳,不能憑空跳躍。
2. 向上跳時,如果上方有檔板,永遠不可能跳過檔板,只要一接近檔板,就自動吸附上去了(仔細看gif最后那段跳躍),這個看上去比較奇怪。

原因如下:

問題1,是因為jump方法中未作任何約束,不管什么時候調用,總是能獲取向上的速度,可以改進為:檢測方法是否站在檔板上(仍然通過碰撞檢測,方塊站在檔板上,肯定就發生了碰撞),只有站在檔板上,調用jump時,才能獲取向上的彈跳速度。

問題2,是因為main.py中,一直在檢測碰撞,向上跳的過程中,如果頭頂有檔板,一碰到檔板,代碼邏輯就強制把方塊固定在檔板上了(即:認為方塊落在檔板上了)。改進方法:僅在下降過程中,才做碰撞檢測。

調試后的sprites.py代碼如下:

from part_04.settings import *
import pygame as pg
import math

vec = pg.math.Vector2


class Player(pg.sprite.Sprite):
    def __init__(self, game):
        pg.sprite.Sprite.__init__(self)
        # 初始化時,要把Game類的實例傳過來
        self.game = game
        self.image = pg.Surface((30, 30))
        self.image.fill(YELLOW)
        self.rect = self.image.get_rect()
        self.rect.center = WIDTH / 2, HEIGHT / 2
        self.pos = self.rect.center
        self.vel = vec(0, 0)
        self.acc = vec(0, 0)
        self.width = self.rect.width
        self.height = self.rect.height

    def jump(self):
        # 只有碰撞了,才能向上跳(即:只有Player站在檔板上了,才能起跳)
        hits = pg.sprite.spritecollide(self, self.game.platforms, False)
        if hits:
            self.vel.y = -22

    def update(self):
        self.acc = vec(0, PLAYER_GRAVITY)
        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.x += self.vel.x * PLAYER_FRICTION

        self.vel += self.acc
        self.pos += self.vel

        if self.rect.left > WIDTH:
            self.pos.x = 0 - self.width / 2
        if self.rect.right < 0:
            self.pos.x = WIDTH + self.width / 2

        #
        if math.fabs(self.rect.bottom - self.pos.y) >= 1:
            self.rect.bottom = self.pos.y
        self.rect.x = self.pos.x - self.width / 2


class Platform(pg.sprite.Sprite):
    def __init__(self, x, y, w, h):
        pg.sprite.Sprite.__init__(self)
        self.image = pg.Surface((w, h))
        self.image.fill(GREEN)
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y

main.py代碼如下:

from part_04.sprites import *
from part_04.settings import *


class Game:

    def __init__(self):
        pg.init()
        pg.mixer.init()
        self.screen = pg.display.set_mode(SIZE)
        pg.display.set_caption(TITLE)
        self.clock = pg.time.Clock()
        self.running = True
        self.playing = False

    def new(self):
        self.all_sprites = pg.sprite.Group()
        self.platforms = pg.sprite.Group()
        self.player = Player(self)
        self.all_sprites.add(self.player)

        for plat in PLATFORM_LIST:
            p = Platform(*plat)
            self.all_sprites.add(p)
            self.platforms.add(p)

        self.run()

    def run(self):
        self.playing = True
        while self.playing:
            self.clock.tick(FPS)
            self.events()
            self.update()
            self.draw()

    def update(self):
        self.all_sprites.update()
        # 只有向下落時,才做碰撞檢測(防止向上跳時,被上方檔板自動吸附)
        if self.player.vel.y > 0:
            hits = pg.sprite.spritecollide(self.player, self.platforms, False)
            if hits:
                self.player.pos.y = hits[0].rect.top
                self.player.vel.y = 0

    def events(self):
        for event in pg.event.get():
            if event.type == pg.QUIT:
                if self.playing:
                    self.playing = False
                self.running = False
            if event.type == pg.KEYDOWN:
                if event.key == pg.K_SPACE:
                    self.player.jump()

    def draw(self):
        self.screen.fill(BLACK)
        self.all_sprites.draw(self.screen)
        self.debug()
        pg.display.flip()

    def debug(self):
        if DEBUG:
            font = pg.font.SysFont('Menlo', 25, True)
            pos_txt = font.render(
                'Pos:(' + str(round(self.player.pos.x, 2)) + "," + str(round(self.player.pos.y, 2)) + ")", 1, GREEN)
            vel_txt = font.render(
                'Vel:(' + str(round(self.player.vel.x, 2)) + "," + str(round(self.player.vel.y, 2)) + ")", 1, GREEN)
            acc_txt = font.render(
                'Acc:(' + str(round(self.player.acc.x, 2)) + "," + str(round(self.player.acc.y, 2)) + ")", 1, GREEN)
            self.screen.blit(pos_txt, (20, 10))
            self.screen.blit(vel_txt, (20, 40))
            self.screen.blit(acc_txt, (20, 70))
            pg.draw.line(self.screen, WHITE, (0, HEIGHT / 2), (WIDTH, HEIGHT / 2), 1)
            pg.draw.line(self.screen, WHITE, (WIDTH / 2, 0), (WIDTH / 2, HEIGHT), 1)

    def show_start_screen(self):
        pass

    def show_go_screen(self):
        pass


g = Game()
g.show_start_screen()
while g.running:
    g.new()
    g.show_go_screen()

pg.quit()

效果如下: 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM