Python 2.7 重力与矩形游戏
我真的有一个基本的问题,需要很长时间。有人能教我怎么做直跳吗?我只需要一个矩形的示例。我看到了你的问题,我想我已经为你做了一些示例代码,但首先我想告诉你它是如何工作的。除了在Y轴上存储位置的Y变量外,还需要一个名为velocityY的变量。对于游戏中的每一帧,Y变量都会用velocityY更改,如下所示:Python 2.7 重力与矩形游戏,python-2.7,pygame,rect,Python 2.7,Pygame,Rect,我真的有一个基本的问题,需要很长时间。有人能教我怎么做直跳吗?我只需要一个矩形的示例。我看到了你的问题,我想我已经为你做了一些示例代码,但首先我想告诉你它是如何工作的。除了在Y轴上存储位置的Y变量外,还需要一个名为velocityY的变量。对于游戏中的每一帧,Y变量都会用velocityY更改,如下所示: while True: y += velocityY # <----- Here manage_window() for event in pygame.even
while True:
y += velocityY # <----- Here
manage_window()
for event in pygame.event.get():
handle_event(event)
pygame.display.flip()
我想艾尔·斯维加特(Al Sweigart)的书中也提到了这一点。我能要一个准确的页面吗?
gravity
是你一直添加到位置上的值,只有与背景碰撞才能阻止你摔倒。请参见第页的“你创建rect
和groundRect`两次”。您可以在的同时在中再次删除。我一直得到这样一个事实,即有很多空参数。我应该把什么作为论点?
import pygame
pygame.init()
window = pygame.display.set_mode((800, 600))
x, y = 300, 400
xVelocity, yVelocity = 0, 0
rect = pygame.Rect(x, y, 200, 200)
groundRect = pygame.Rect(0, 500, 800, 100)
clock = pygame.time.Clock()
white = 255, 255, 255
red = 255, 0, 0
black = 0, 0, 0
blue = 0, 0, 255
while True:
clock.tick(60) # Make sure the game is running at 60 FPS
rect = pygame.Rect(x, y, 200, 200) # Updating our rect to match coordinates
groundRect = pygame.Rect(0, 500, 800, 100) # Creating ground rect
# HERE IS WHAT YOU CARE ABOUT #
yVelocity += 0.2 # Gravity is pulling the rect down
x += xVelocity # Here we update our velocity on the X axis
y += yVelocity # Here we update our velocity on the Y axis
# HERE IS WHAT YOU CARE ABOUT #
if groundRect.colliderect(rect): # Check if the rect is colliding with the ground
y = groundRect.top-rect.height
yVelocity = 0
window.fill(white)
pygame.draw.rect(window, red, rect) # Here we draw the rect
pygame.draw.rect(window, black, rect, 5) # Here we draw the black box around the rect
pygame.draw.rect(window, blue, groundRect) # Here we draw the ground
pygame.draw.rect(window, black, groundRect, 5) # Here we draw the black box around the rect
for event in pygame.event.get(): # Getting events
if event.type == pygame.QUIT: # If someone presses X on the window, then we want to quit
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE: # Pressing space will make the cube jump
if y >= 300: # Checking if cube is on the ground and not in the air
yVelocity = -10 # Setting velocity to upwards
pygame.display.flip() # Updating the screen