【问题标题】:How to make a circular object jump using pygame? [duplicate]如何使用pygame使圆形物体跳跃? [复制]
【发布时间】:2020-07-09 19:30:51
【问题描述】:

我刚开始使用,但我卡住了。

我没有收到任何语法错误,但我确定以下代码存在一些问题。

import pygame
import sys

pygame.init()
pygame.display.set_caption('Jumper Game')

display_width = 500
display_height = 500
the_game_is_on = True

ball_pos_x = 200
ball_pos_y = 500
ball_radius = 20
ball_color = [0,0,255]
speed = 1

is_jump = False
m = 1
v = 5

dis = pygame.display.set_mode((display_width,display_height)) #screen

while the_game_is_on:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT] and ball_pos_x > 20:
        ball_pos_x-= speed
    if keys[pygame.K_RIGHT] and ball_pos_x < (display_width - (ball_radius)):
        ball_pos_x+= speed
    if not (is_jump):
        if keys[pygame.K_UP] and ball_pos_y > 20:
            ball_pos_y-= speed
        if keys[pygame.K_DOWN] and ball_pos_y < (display_height - (ball_radius)):
            ball_pos_y+= speed
        if keys[pygame.K_SPACE]:
            is_jump = True
    else:
        f = (1/2)*m*(v**2)
        ball_pos_y-=f
        v-=1
        if v < 0:
            m = -1
        if v >= ((v+1)*-1): #to check the initial position
            is_jump = False
    pygame.time.delay(10)
    dis.fill((0,0,0))
    pygame.draw.circle(dis,ball_color,(ball_pos_x,int(ball_pos_y)),ball_radius)
    pygame.display.update()
pygame.display.quit()

关于跳转的代码,我参考了这个website,这个网站的源代码完美运行。

【问题讨论】:

  • 有些问题吧?需要详细说明吗?
  • “一些问题”实际上并没有什么特别的意思,我不希望这里有太多用户对分析您的代码感兴趣,只是为了弄清楚您想问什么。
  • 是的,所以蓝色球在横向、上下移动时效果很好。但是当我按下空格键时它突然消失了。 @JoranBeasley
  • 尝试在击中空间后打印出球的 y 位置。我怀疑球会飞向疯狂的高位或低位,在相机中无法很快看到。

标签: pygame python python-3.x pygame


【解决方案1】:

你必须在v &lt; 0上计算mdependnet:

m = -1 if v < 0 else 1

如果v &lt; -5,跳转必须结束,当跳转结束时,v必须重置(v = 5):

jump_h = 5 # try 10 for higher jumps
v = jump_h

while the_game_is_on:
    # [...]

    if not is_jump:
        # [...]

    else:
        if v >= -jump_h:
            m = -1 if v < 0 else 1
            f = (1/2)*m*(v**2)
            v -=1
            ball_pos_y -= f
        else:
            is_jump = False
            v = jump_h

【讨论】:

  • 非常感谢@Rabbid76
【解决方案2】:

我认为您正在了解 Python2 与 Python3 的区别:

$ python3
Python 3.7.7 (default, Mar 13 2020, 21:39:43) 
[GCC 9.2.1 20190827 (Red Hat 9.2.1-1)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> m = 1
>>> v = 5
>>> (1/2)*m*(v**2)
12.5

在 Python2 中,1 / 2 等于 0,但是当你使用浮点数时:1.0 / 20.5

$ python2
Python 2.7.18 (default, Apr 21 2020, 18:49:31) 
[GCC 9.3.1 20200408 (Red Hat 9.3.1-2)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> m = 1
>>> v = 5
>>> (1/2)*m*(v**2)
0
>>> (float(1)/2)*m*(v**2)
12.5

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多