#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ 跳跃脚本 - 让对象产生上下跳跃效果 """ from core.script_system import ScriptBase import math class BouncerScript(ScriptBase): """跳跃脚本类""" def __init__(self): super().__init__() # 跳跃参数 self.jump_height = 2.0 # 跳跃高度 self.jump_speed = 3.0 # 跳跃速度 (跳跃/秒) self.bounce_type = "sine" # 跳跃类型: "sine", "abs_sine", "square" # 内部变量 self.time_accumulator = 0.0 # 时间累积器 self.original_y = None # 原始Y位置 self.is_bouncing = True # 是否正在跳跃 self.bounce_direction = 1 # 跳跃方向 def start(self): """脚本开始时调用""" self.log("跳跃脚本启动!") self.log(f"跳跃参数: 高度={self.jump_height}, 速度={self.jump_speed}, 类型={self.bounce_type}") # 记录原始Y位置 self.original_y = self.gameObject.getZ() # Z轴是高度 self.log(f"原始高度: {self.original_y}") def update(self, dt): """每帧更新""" if not self.is_bouncing: return # 累积时间 self.time_accumulator += dt * self.bounce_direction # 根据类型计算跳跃高度 if self.bounce_type == "sine": # 标准正弦波跳跃 height_offset = math.sin(self.time_accumulator * self.jump_speed * 2 * math.pi) * self.jump_height elif self.bounce_type == "abs_sine": # 绝对值正弦波(始终向上) height_offset = abs(math.sin(self.time_accumulator * self.jump_speed * 2 * math.pi)) * self.jump_height elif self.bounce_type == "square": # 方波跳跃(突然跳起落下) sine_val = math.sin(self.time_accumulator * self.jump_speed * 2 * math.pi) height_offset = self.jump_height if sine_val > 0 else 0 else: height_offset = 0 # 应用跳跃 current_pos = self.gameObject.getPos() new_z = self.original_y + height_offset self.gameObject.setPos(current_pos.getX(), current_pos.getY(), new_z) def set_bounce_parameters(self, height=None, speed=None, bounce_type=None): """设置跳跃参数""" if height is not None: self.jump_height = height if speed is not None: self.jump_speed = speed if bounce_type is not None and bounce_type in ["sine", "abs_sine", "square"]: self.bounce_type = bounce_type self.log(f"跳跃参数更新: 高度={self.jump_height}, 速度={self.jump_speed}, 类型={self.bounce_type}") def toggle_bouncing(self): """切换跳跃状态""" self.is_bouncing = not self.is_bouncing status = "恢复" if self.is_bouncing else "暂停" self.log(f"跳跃{status}") def reverse_direction(self): """反转跳跃方向""" self.bounce_direction *= -1 direction = "正向" if self.bounce_direction > 0 else "反向" self.log(f"跳跃方向改为{direction}") def reset_position(self): """重置到原始高度""" if self.original_y is not None: current_pos = self.gameObject.getPos() self.gameObject.setPos(current_pos.getX(), current_pos.getY(), self.original_y) self.time_accumulator = 0.0 self.log("位置已重置到原始高度") def jump_once(self): """执行一次跳跃""" self.time_accumulator = 0.0 self.log("执行单次跳跃") def on_destroy(self): """脚本销毁时调用""" self.log("跳跃脚本停止")