[英]What would be an effective way to do traps in pygame?
Been working on a game inspired from a game called 'I wanna be the guy', and I've moved onto traps.一直在开发一款灵感来自一款名为“我想成为那个人”的游戏,我已经转向了陷阱。 The problem is I've been stuck on how to activate them and make them shoot up and kill the player.
问题是我一直在思考如何激活它们并使它们射击并杀死玩家。
Here's what I have been working with:这是我一直在使用的:
#parent class
class Sprite(pygame.sprite.Sprite):
def __init__(self, img, x, y):
super().__init__()
self.image = img
self.rect = self.image.get_rect()
self.initial_x = x
self.initial_y = y
self.reset()
def reset(self):
self.rect.x = self.initial_x
self.rect.y = self.initial_y
#child class inheriting from Sprite
class autoHazard(Sprite):
def set(self, x_speed, y_speed):
self.counter = 0
self.triggered()
if self.counter == 1:
self.rect.x += x_speed
self.rect.y += y_speed
hit = pygame.sprite.collide_rect(self, play)
if hit:
play.kill()
def triggered(self):
if play.rect.x >= self.rect.x - 76:
self.counter = 1
#main file
... code
#outside main program loop
Trap = autoHazard(img.lul_img, 1000, con.height - 100)
grp.all_sprites.add(Trap)
Trap2 = autoHazard(img.lul_img, 800, con.height - 100)
grp.all_sprites.add(Trap2)
... code
#inside main program loop
... code
Trap.set(0,-20)
Trap2.set(0,-20)
... code
What instead happens is that it will move up, but it is restricted by the if statement in autoHazard
, which will make it only move when player position x
is greater than the trap's x
position.相反,它会向上移动,但它受到
autoHazard
的 if 语句的autoHazard
,这将使它仅在玩家位置x
大于陷阱的x
位置时移动。 What I want is for the trap to shoot up and not get deactivated if the if statement condition is not met.我想要的是如果不满足 if 语句条件,则陷阱会弹出并且不会被停用。
What I want is for the trap to shoot up and not get deactivated
我想要的是让陷阱弹起来而不被停用
The issue is, that self.counter
is set 0 every time when autoHazard.set
is called.问题是,每次调用
autoHazard.set
时, self.counter
都会设置为 0。 If you want to make this state persistent then you have to remove self.counter = 0
form autoHazard.set
.如果你想使这个状态持续,那么你必须删除
self.counter = 0
形式autoHazard.set
。 Initialize self.counter = 0
in the constructor:在构造函数中初始化
self.counter = 0
:
class autoHazard(Sprite):
def __init__(self, img, x, y):
super().__init__()
# [...]
self.counter = 0
def set(self, x_speed, y_speed):
if self.counter == 0:
self.triggered()
if self.counter == 1:
self.rect.x += x_speed
self.rect.y += y_speed
hit = pygame.sprite.collide_rect(self, play)
if hit:
play.kill()
def triggered(self):
if play.rect.x >= self.rect.x - 76:
self.counter = 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.