根据鼠标位置添加一个力。
处理鼠标位置:
mouse_pos = Vector2(pygame.mouse.get_pos())
在游戏循环中,可以创建一个事件来对鼠标位置进行更新:
for event in pygame.event.get():
if event.type == pygame.MOUSEMOTION:
mouse_pos = Vector2(pygame.mouse.get_pos())
为对象添加一个力:
force_direction = mouse_pos - object_position
force_direction.normalize() # 应该总是规范化(标准化)
object.add_force(force_direction)
在这里,force_direction
表示从对象位置到鼠标位置的向量,normalize()
函数可以将其规范化为长度为 1 的向量,然后将其与对象的添加力进行合并。
完整代码示例:
import pygame
from pygame.math import Vector2
class GameObject:
def __init__(self, x, y):
self.position = Vector2(x, y)
self.velocity = Vector2(0, 0)
self.acceleration = Vector2(0, 0)
def add_force(self, force):
self.acceleration += force
def update(self):
self.velocity += self.acceleration
self.position += self.velocity
self.acceleration *= 0
pygame.init()
screen = pygame.display.set_mode((640, 480))
clock = pygame.time.Clock()
objects = []
for i in range(20):
position = Vector2(pygame.math.Vector2(random.randrange(0, 640), random.randrange(0, 480)))
object = GameObject(*position)
objects.append(object)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.MOUSEMOTION:
mouse_pos = Vector2(pygame.mouse.get_pos())
for object in objects:
force_direction = mouse_pos - object.position
force_direction.normalize() # 极其重要的规范化
object.add_force(force_direction)
screen.fill((255, 255, 255))
for object in objects:
object.update()
pygame.draw.circle(screen, (0, 0, 0), object.position, 10)
pygame.display.flip()
clock.tick(60)