小能豆

如何沿方形路径反复移动物体?

py

所以基本上我想要发生的事情是,每当物体到达终点时,它就会向屏幕的各个方向移动。例如,如果我走了,->然后如果我到达终点,downward然后如果我到达终点,<-然后如果我到达终点,然后upward它不断重复。这是代码。

import pygame

#Initialize Game
pygame.init()

#Create a screen (width,height)
screen = pygame.display.set_mode((550,725))

#Title and icon
pygame.display.set_caption('Bounce')
icon = pygame.image.load('assets/ball.png')
court = pygame.image.load('assets/court.png')
pygame.display.set_icon(icon)
clock = pygame.time.Clock()

def ball(x,y):
    screen.blit(icon,(x,y))

def court_(x,y):
    screen.blit(court,(x,y))

x = 430
y = 630

direction = "right" #Directions

running = True
while running:

#background
  screen.fill((255,175,0)) 


  for event in pygame.event.get():
      if event.type == pygame.QUIT:
          running = False

  if direction == "right":
      x -= 2
  if direction == "left":
      x += 2
  if direction == "up":
      y -= 2
  if direction == "down":
      y += 2

  if x <= 30: 
      direction = "up"
  if y <= 30:
      direction = "left"
  if x >= 430:
      direction = "down"
  if y == 630:
      direction = "right"

  court_(0,0)
  ball(x,y)

  pygame.display.update()
  clock.tick(60)

阅读 20

收藏
2025-01-02

共1个答案

小能豆

对于一般方法,定义一个角点列表、速度和列表中下一个点的索引:

x, y = 430, 630
corner_points = [(430, 630), (30, 630), (30, 30), (430, 20)]
speed = 2
next_pos_index = 1

在应用程序循环中将对象从点移动到点:

circle_dir = pygame.math.Vector2(corner_points[next_pos_index]) - (x, y)
if circle_dir.length() < speed:
    x, y = corner_points[next_pos_index]
    next_pos_index = (next_pos_index + 1) % len(corner_points)
else:
    circle_dir.scale_to_length(speed)
    new_pos = pygame.math.Vector2(x, y) + circle_dir
    x, y = (new_pos.x, new_pos.y) 

根据您的代码的最小示例:

img

import pygame

pygame.init()
screen = pygame.display.set_mode((550,725))
clock = pygame.time.Clock()

x, y = 430, 630
corner_points = [(430, 630), (30, 630), (30, 30), (430, 20)]
speed = 2
next_pos_index = 1

def move(x, y, speed, points, i):
    circle_dir = pygame.math.Vector2(points[i]) - (x, y)
    if circle_dir.length() < speed:
        x, y = points[i]
        i = (i + 1) % len(points)
    else:
        circle_dir.scale_to_length(speed)
        new_pos = pygame.math.Vector2(x, y) + circle_dir
        x, y = (new_pos.x, new_pos.y) 
    return x, y, i

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    x, y, next_pos_index = move(x, y, speed, corner_points, next_pos_index)

    screen.fill((255,175,0)) 
    pygame.draw.circle(screen, "blue", (x, y), 20)
    pygame.display.update()
    clock.tick(60)
2025-01-02