python - 如何让我的玩家与平台 pygame 发生碰撞
问题描述
如何让我的播放器与我的平台发生碰撞?
我知道如何让玩家移动、跳跃以及如何添加墙壁。我还知道如何为我的播放器制作图像,如何制作形状以及 python 和其他东西的大部分基础知识。我正在学习 python,我是 pygame 的新手。
这是我的播放器代码:
class player:
def __init__(self,x,y,width,height,color):
self.x = x
self.y = y
self.width = width
self.height = height
self.color = color
self.speed = 5
self.isJump = False
self.JumpCount = 10
self.ss1 = pygame.image.load("G5.png")
self.rect = pygame.Rect(x,y,height,width)
def draw(self):
self.rect.topleft = (self.x,self.y)
window.blit(self.ss1,self.rect)
这是我的完整代码:
import pygame
pygame.init()
#this is screem height
window = pygame.display.set_mode((500,500))
#know we put screem name
pygame.display.set_caption("Noobs first Game")
#player class
class player:
def __init__(self,x,y,width,height,color):
self.x = x
self.y = y
self.width = width
self.height = height
self.color = color
self.speed = 5
self.isJump = False
self.JumpCount = 10
self.ss1 = pygame.image.load("G5.png")
self.rect = pygame.Rect(x,y,height,width)
def draw(self):
self.rect.topleft = (self.x,self.y)
window.blit(self.ss1,self.rect)
class enemy:
def __init__(self,x,y,height,width,color):
self.x = x
self.y = y
self.height = height
self.width = width
self.color = color
self.rect = pygame.Rect(x,y,height,width)
def draw(self):
self.rect.topleft=(self.x,self.y)
pygame.draw.rect(window,self.color,self.rect)
#player and enemy
white = (255,255,255)
player1 = player(0,400,60,60,white)
red = (255,48,48)
enemy1 = enemy(100,100,60,20,red)
#window
def redrawwindow():
window.fill((0,0,0))
#player draw
player1.draw()
enemy1.draw()
fps = (30)
clock = pygame.time.Clock()
run = True
while run:
clock.tick(fps)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
keys = pygame.key.get_pressed()
if keys[pygame.K_a]and player1.x > player1.speed:
player1.x -= player1.speed
if keys[pygame.K_d]and player1.x <500 - player1.height - player1.speed:
player1.x += player1.speed
if keys[pygame.K_w]and player1.y > player1.speed:
player1.y -= player1.speed
if keys[pygame.K_s]and player1.y <500 - player1.width - player1.speed:
player1.y += player1.speed
if not(player1.isJump):
if keys[pygame.K_SPACE]:
player1.isJump = True
else:
if player1.JumpCount >= -10:
player1.y -= (player1.JumpCount*abs(player1.JumpCount))*0.5
player1.JumpCount -= 1
else:
player1.isJump = False
player1.JumpCount = 10
redrawwindow()
pygame.display.update()
pygame.quit()
```
解决方案
首先,欢迎堆栈溢出。您的第一个问题很好,因为您提供了详细信息、代码并且问题具体。试着修正你的语法和标点符号,让它更容易阅读。
就您的问题而言,您想检查播放器是否与
if player.rect.colliderect(enemy.rect):
然后相应地移动它们。例如,检查速度并将它们向相反方向移动少量。
推荐阅读
- android - 如何将文本文件附加到默认 gmail?附件 toast 的权限被拒绝
- python - 多对多嵌套关系作为 Django Rest 框架中的列表
- xcode - Xcode 找不到头文件,尽管它已添加到头搜索路径中
- r - ggplot2:仅将 hline 添加到一个网格
- javascript - 如何将数据从列表组项传递到 PHP 文件?
- excel - 使用 VBA 抓取 Outlook 电子邮件 - 类型不匹配
- jenkins - Jenkins Pipeline 作业 - 作业描述上没有阶段 UI
- javascript - 角停止输入键提交
- bash - bash:将垂直多行输出分配给变量并获取元素摘要
- ios - 改变标签的约束