我真的有一个基本的问题,需要一个长的芒果。有人能告诉我如何制作一个Rect跳?我只需要一个带矩形的样本。
答案 0 :(得分:1)
我看到了你的问题,我想我已经为你做了一些示例代码,但首先我想告诉你它是如何工作的。除了用于在Y轴上存储位置的Y变量之外,还需要一个名为velocityY的变量。对于游戏中的每一帧,Y变量都用velocityY改变,如下所示:
while True:
y += velocityY # <----- Here
manage_window()
for event in pygame.event.get():
handle_event(event)
pygame.display.flip()
当你跳跃时,你将velocityY设置为-10,这将使你的直线飞向天空,所以我们需要增加重力。这是一个很长的例子(重要的部分是):
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