|
|
@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
import pygame
|
|
|
|
|
|
|
|
from math import sin
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class Entity(pygame.sprite.Sprite):
|
|
|
|
|
|
|
|
def __init__(self,groups):
|
|
|
|
|
|
|
|
# 初始化精灵对象,将其添加到指定的精灵组中
|
|
|
|
|
|
|
|
super().__init__(groups)
|
|
|
|
|
|
|
|
# 当前动画帧的索引,初始值为 0
|
|
|
|
|
|
|
|
self.frame_index = 0
|
|
|
|
|
|
|
|
# 动画播放速度,控制动画切换的速度
|
|
|
|
|
|
|
|
self.animation_speed = 0.15
|
|
|
|
|
|
|
|
# 实体对象的移动方向向量,初始为零向量
|
|
|
|
|
|
|
|
self.direction = pygame.math.Vector2()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def move(self,speed):
|
|
|
|
|
|
|
|
# 检查移动方向向量的大小是否不为零
|
|
|
|
|
|
|
|
if self.direction.magnitude() != 0:
|
|
|
|
|
|
|
|
# 将移动方向向量归一化(单位化),确保移动方向的长度为1,用于保持移动速度的一致性和准确性
|
|
|
|
|
|
|
|
self.direction = self.direction.normalize()
|
|
|
|
|
|
|
|
# 更新碰撞箱(hitbox)的水平位置
|
|
|
|
|
|
|
|
self.hitbox.x += self.direction.x * speed
|
|
|
|
|
|
|
|
# 进行水平方向上的碰撞检测和处理
|
|
|
|
|
|
|
|
self.collision('horizontal')
|
|
|
|
|
|
|
|
# 更新碰撞箱(hitbox)的垂直位置
|
|
|
|
|
|
|
|
self.hitbox.y += self.direction.y * speed
|
|
|
|
|
|
|
|
# 进行垂直方向上的碰撞检测和处理
|
|
|
|
|
|
|
|
self.collision('vertical')
|
|
|
|
|
|
|
|
# 更新实体对象的外部矩形(rect)的中心位置,确保渲染时显示在正确的位置
|
|
|
|
|
|
|
|
self.rect.center = self.hitbox.center
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# 根据传入的方向进行碰撞检测和处理
|
|
|
|
|
|
|
|
def collision(self,direction):
|
|
|
|
|
|
|
|
# 检测水平方向上的碰撞
|
|
|
|
|
|
|
|
if direction == 'horizontal':
|
|
|
|
|
|
|
|
# 检测当前实体对象的碰撞箱与障碍物精灵的碰撞箱是否相交
|
|
|
|
|
|
|
|
for sprite in self.obstacle_sprites:
|
|
|
|
|
|
|
|
if sprite.hitbox.colliderect(self.hitbox):
|
|
|
|
|
|
|
|
# 向右移动
|
|
|
|
|
|
|
|
if self.direction.x > 0:
|
|
|
|
|
|
|
|
# 调整碰撞箱的右侧边界为障碍物的左侧边界
|
|
|
|
|
|
|
|
self.hitbox.right = sprite.hitbox.left
|
|
|
|
|
|
|
|
# 向左移动
|
|
|
|
|
|
|
|
if self.direction.x < 0:
|
|
|
|
|
|
|
|
# 调整碰撞箱的左侧边界为障碍物的右侧边界
|
|
|
|
|
|
|
|
self.hitbox.left = sprite.hitbox.right
|
|
|
|
|
|
|
|
# 检测垂直方向上的碰撞
|
|
|
|
|
|
|
|
if direction == 'vertical':
|
|
|
|
|
|
|
|
# 检测当前实体对象的碰撞箱与障碍物精灵的碰撞箱是否相交
|
|
|
|
|
|
|
|
for sprite in self.obstacle_sprites:
|
|
|
|
|
|
|
|
if sprite.hitbox.colliderect(self.hitbox):
|
|
|
|
|
|
|
|
# 向下移动
|
|
|
|
|
|
|
|
if self.direction.y > 0:
|
|
|
|
|
|
|
|
# 调整碰撞箱的底部边界为障碍物的顶部边界
|
|
|
|
|
|
|
|
self.hitbox.bottom = sprite.hitbox.top
|
|
|
|
|
|
|
|
# 向上移动
|
|
|
|
|
|
|
|
if self.direction.y < 0:
|
|
|
|
|
|
|
|
# 调整碰撞箱的顶部边界为障碍物的底部边界
|
|
|
|
|
|
|
|
self.hitbox.top = sprite.hitbox.bottom
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def wave_value(self):
|
|
|
|
|
|
|
|
# 获取当前游戏时间的正弦值
|
|
|
|
|
|
|
|
value = sin(pygame.time.get_ticks())
|
|
|
|
|
|
|
|
# 如果正弦值大于等于0,则返回255,否则返回0
|
|
|
|
|
|
|
|
if value >= 0:
|
|
|
|
|
|
|
|
return 255
|
|
|
|
|
|
|
|
else:
|
|
|
|
|
|
|
|
return 0
|