當它移動到屏幕大小的10%時,我想讓我的「球」(player1
)「反彈」。現在,它停止加速。我該如何讓球彈跳?
我很確定我必須做些什麼與self.vel["x_vel"]["x_dir"]
和self.vel["y_vel"]["y_dir"]
。我認爲通過設置self.vel["x_vel"]["x_mag"]
和self.vel["y_vel"]["y_mag"]
等於零,它會完全停止移動,但它只是停止加速。我還認爲,通過將self.vel["x_vel"]["x_dir"]
和self.vel["y_vel"]["y_dir"]
乘以-1,我會「翻轉」它正在移動的方向,但這樣做似乎沒有影響任何東西。
當我說我想讓它「反彈」時,我的意思是我希望它立即停止,反向並沿着玩家按下的任何方向行進。例如,如果你從一開始就持有s,我會希望它看起來像你掉了一個球。
import sys
import pygame
pygame.init()
screen_width = 640
screen_height = 480
screen = pygame.display.set_mode((screen_width, screen_height))
screen_rect = screen.get_rect()
clock = pygame.time.Clock()
fps = 30
class Character(object):
def __init__(self, surface):
self.surface = surface
self.x_mag = 0
self.y_mag = 0
self.x_dir = 0
self.y_dir = 0
self.vel = {"x_vel":
{"x_mag": self.x_mag, "x_dir": self.x_dir},
"y_vel":
{"y_mag": self.y_mag, "y_dir": self.y_dir}}
self.x_pos = (screen_width/2)
self.y_pos = (screen_height/2)
self.pos = {"x_pos": self.x_pos, "y_pos": self.y_pos}
self.size = (10, 10)
def move_right(self):
self.vel["x_vel"]["x_dir"] = 1
self.vel["y_vel"]["y_dir"] = 0
self.vel["x_vel"]["x_mag"] += 5
self.pos["x_pos"] += (self.vel["x_vel"]["x_mag"] * self.vel["x_vel"]["x_dir"])
def move_left(self):
self.vel["x_vel"]["x_dir"] = 1
self.vel["y_vel"]["y_dir"] = 0
self.vel["x_vel"]["x_mag"] -= 5
self.pos["x_pos"] += (self.vel["x_vel"]["x_mag"] * self.vel["x_vel"]["x_dir"])
def move_up(self):
self.vel["x_vel"]["x_dir"] = 0
self.vel["y_vel"]["y_dir"] = 1
self.vel["y_vel"]["y_mag"] -= 5
self.pos["y_pos"] += (self.vel["y_vel"]["y_mag"] * self.vel["y_vel"]["y_dir"])
def move_down(self):
self.vel["x_vel"]["x_dir"] = 0
self.vel["y_vel"]["y_dir"] = 1
self.vel["y_vel"]["y_mag"] += 5
self.pos["y_pos"] += (self.vel["y_vel"]["y_mag"] * self.vel["y_vel"]["y_dir"])
def move(self):
keys = pygame.key.get_pressed()
if keys[pygame.K_w]:
self.move_up()
if keys[pygame.K_a]:
self.move_left()
if keys[pygame.K_s]:
self.move_down()
if keys[pygame.K_d]:
self.move_right()
if self.pos["x_pos"] <= (screen_width * .1) or self.pos["x_pos"] >= (screen_width * .9):
self.vel["x_vel"]["x_mag"] = 0
self.vel["x_vel"]["x_dir"] *= -1
if self.pos["y_pos"] <= (screen_height * .1) or self.pos["y_pos"] >= (screen_height * .9):
self.vel["y_vel"]["y_mag"] = 0
self.vel["y_vel"]["y_dir"] *= -1
self.character = pygame.Rect((self.pos["x_pos"], self.pos["y_pos"]), self.size)
def display(self):
pygame.draw.rect(self.surface, (255, 255, 255), self.character)
def main():
player1 = Character(screen)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
player1.move()
screen.fill((0, 0, 0))
player1.display()
pygame.display.update(screen_rect)
clock.tick(fps)
if __name__ == "__main__":
main()
我不知道pygame的東西,但在我看來,當你設置你的速度矢量的大小爲0, '說停止移動。儘量不要觸及數量級,只是翻轉方向。 – cHao
@cHao我試過了,球剛剛加速離開屏幕。雖然只是在不改變幅度的情況下改變方向對我來說很有意義。我沒有按照方向做正確的事,但我不知道是什麼。 – user44557
那麼......在你的「移動」功能中,這並不是真的有幫助,你使用的是幅度,而當你檢查反彈時,你使用方向。首先使用兩個數字有什麼特別的原因嗎? – cHao