You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决Ursina中camera.add_script(SmoothFollow())失效问题

问题解决:Ursina相机添加SmoothFollow脚本无效

问题原因

  1. Player类的update方法中误用全局变量player修改位置,存在作用域风险;
  2. Ursina的Camera作为特殊实体,直接添加移动脚本可能与引擎内部逻辑冲突,导致跟随失效。

修复方案

方案1:通过父节点代理实现相机跟随(推荐)

创建空实体作为相机的父节点,将SmoothFollow脚本添加到父节点上,避免相机自身逻辑干扰:

from ursina import *

class Player(Entity):
    def __init__(self):
        super(Player, self).__init__(
            model='quad',
            scale=1,
            parent='scene',
            color=color.green
        )
        self.speed = 5

    def update(self):
        # 使用self指代当前Player实例,避免全局变量问题
        move_direction = Vec2(held_keys['d']-held_keys['a'], held_keys['w']-held_keys['s']).normalized()
        self.position += move_direction * self.speed * time.dt

app = Ursina()

player = Player()
camera.orthographic = True
camera.fov = 20

# 创建空实体作为相机父节点,挂载跟随脚本
camera_parent = Entity()
camera.parent = camera_parent
camera_parent.add_script(SmoothFollow(target=player, speed=8, offset=[0, 0, -4]))

app.run()

方案2:修正Player类的变量引用(若坚持直接给相机加脚本)

先修复Player类中位置更新的变量问题,再尝试给相机添加脚本:

from ursina import *

class Player(Entity):
    def __init__(self):
        super(Player, self).__init__(
            model='quad',
            scale=1,
            parent='scene',
            color=color.green
        )
        self.speed = 5

    def update(self):
        move_direction = Vec2(held_keys['d']-held_keys['a'], held_keys['w']-held_keys['s']).normalized()
        self.position += move_direction * self.speed * time.dt

app = Ursina()

player = Player()
camera.orthographic = True
camera.fov = 20
# 修正Player类后,尝试直接给相机加脚本(部分场景下可生效)
camera.add_script(SmoothFollow(target=player, speed=8, offset=[0, 0, -4]))

app.run()

说明

Camera作为Ursina的核心实体,内部有默认的位置更新逻辑,直接挂载移动脚本容易出现优先级冲突。通过父节点代理的方式可以完全隔离这种冲突,保证跟随功能稳定运行。同时,使用self代替全局变量是更规范的面向对象写法,能避免潜在的作用域错误。

内容的提问来源于stack exchange,提问作者ovenshyt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 16:08:13