Ursina引擎敌人无法移动问题求助(附相关代码)
问题分析与解决方案
核心问题:移动逻辑错误
你在simulate_moving方法中的循环逻辑完全不符合预期,导致移动行为异常:
# 错误代码 if move_by_random == 'x': for _ in range(int(self.position.x + move_on)): self.position.x += 1
这段代码的循环次数是当前x坐标 + 随机移动距离,比如初始x为16.328、随机move_on为5时,循环次数是21次,敌人会瞬间从x=16.328跳到x=37.328——要么你没察觉到瞬间移动,要么移动后超出了视野范围,看起来像没移动。
修复步骤
1. 修正移动逻辑
根据需求选择以下两种方式:
方式一:瞬间移动(匹配间隔移动的预期)
修改simulate_moving方法,直接让敌人移动指定距离:
def simulate_moving(self): """Simulate enemy moving.""" move_by = ['x', 'z'] move_by_random = choice(move_by) move_on = randint(5, 10) if move_by_random == 'x': self.position.x += move_on elif move_by_random == 'z': self.position.z += move_on self.ai_log(f'Moved {move_on} units along {move_by_random} axis.')
方式二:平滑移动(更自然的视觉效果)
如果希望敌人平滑移动到目标位置,改用Ursina的animate方法:
# 保留__init__中的Sequence逻辑 self.sequences = [ Sequence( Func(self.simulate_moving), Wait(self.move_every_secs), loop=True ) ] # 修改simulate_moving方法 def simulate_moving(self): """Simulate enemy moving smoothly.""" move_by = ['x', 'z'] move_by_random = choice(move_by) move_on = randint(5, 10) duration = 1 # 移动持续时间,单位秒 if move_by_random == 'x': target_x = self.position.x + move_on self.animate('x', target_x, duration=duration) elif move_by_random == 'z': target_z = self.position.z + move_on self.animate('z', target_z, duration=duration) self.ai_log(f'Start moving {move_on} units along {move_by_random} axis.')
2. 修正模型定义问题
你的ENEMY_MODEL = Capsule()是错误的,Capsule()是创建Entity实例,而Ursina的model参数需要模型名称字符串、Mesh对象或路径,改为内置胶囊模型:
ENEMY_MODEL = 'capsule' # 替换原来的Capsule()
3. 简化AI启动逻辑(可选)
可以将update方法简化,保持逻辑清晰:
def update(self): if self.ai_enabled and not self.sequences_started: for sequence in self.sequences: sequence.start() self.sequences_started = True elif not self.ai_enabled and self.sequences_started: for sequence in self.sequences: sequence.pause() self.sequences_started = False
测试验证
修改后运行游戏,敌人会每隔5秒随机沿x或z轴移动5-10个单位,控制台会输出对应的日志,场景中也能看到敌人的位置变化。
内容的提问来源于stack exchange,提问作者sad
相关产品推荐
相关产品推荐

