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

Godot中如何修改新创建实例的变量?激光实例化报错求助

问题:激光眼睛障碍物的位置与朝向设置问题

我正在为即将推出的游戏制作一个简单障碍物:一只会在一定时间后发射激光的眼睛。目前定时器和激光实例化功能已正常工作,但设置激光初始位置与朝向的操作遇到困难。

补充上下文

  • probe是位于眼睛前方20单位处的Area2D;
  • 游戏为方形瓦片地图,每个瓦片大小20单位;
  • Direction是Eye和其发射的激光都具备的整数变量;
  • 仅if (pause == 0)内的代码出现问题。

错误信息

'Node' does not contain a definition for 'Position' and no accessible extension method 'Position' accepting a first argument of type 'Node' could be found
'Node' does not contain a definition for 'Direction' and no accessible extension method 'Direction' accepting a first argument of type 'Node' could be found
The name 'Direction' does not exist in the current context

相关代码

// Called when the node enters the scene tree for the first time.
public override void _Ready()
{
    probe = GetNode<Area2D>("FacingProbe");
    lidSprite = GetNode<AnimatedSprite2D>("EvilEyeLid");
    ballSprite = GetNode<AnimatedSprite2D>("EvilEyeBall");
    ballSprite.Play("Idle");
    switch (direction)
    {
        case 1: lidSprite.Rotation = 3.1416f; probe.Position = new Vector2(-20,0); break;
        case 2: lidSprite.Rotation = 0; probe.Position = new Vector2(20,0); break;
        case 3: lidSprite.Rotation = 4.712f; probe.Position = new Vector2(0,-20); break;
        case 4: lidSprite.Rotation = 1.5708f; probe.Position = new Vector2(0,20); break;
    }
}

// Called every frame. 'delta' is the elapsed time since the previous frame.
public override void _Process(double delta)
{
    if (pause == 0)
    {
        var packedLazer = GD.Load<PackedScene>("res://Entities/Lazer.tscn");
        var lazer = packedLazer.Instantiate();
        lazer.Position = probe.Position;
        lazer.Direction = Direction;
        AddChild(lazer);
    }
    animations();
}

Inspector面板说明

  • EvilEye面板:显示了名为direction的整数导出变量,当前值为2;
  • Lazer面板:显示了名为Direction的整数导出变量。

问题分析与解决方法

1. 类型转换错误

packedLazer.Instantiate()默认返回Node类型,而Position是Node2D及其子类的属性,Direction是激光脚本的自定义变量,Node类型无法直接访问这些内容。需要将实例化对象转换为激光对应的脚本类型(假设激光脚本类名为Lazer):

// 替换原实例化代码
var lazer = packedLazer.Instantiate<Lazer>();

2. 变量名大小写不匹配

你的Eye类中使用的是小写的direction(参考_Ready方法里的switch (direction)),但代码里写的是大写的Direction,导致变量未找到错误。修改为一致的变量名:

lazer.Direction = direction;

3. 性能优化(可选)

当前每帧都会加载Lazer.tscn,会造成性能浪费,建议将场景加载移到_Ready方法中:

private PackedScene packedLazer;

public override void _Ready()
{
    // ... 原有初始化代码
    packedLazer = GD.Load<PackedScene>("res://Entities/Lazer.tscn");
}

public override void _Process(double delta)
{
    if (pause == 0)
    {
        var lazer = packedLazer.Instantiate<Lazer>();
        lazer.Position = probe.Position;
        lazer.Direction = direction;
        AddChild(lazer);
        // 注意:此处需添加逻辑将pause设为非0,否则会每帧生成激光
    }
    animations();
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 03:05:17