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

Godot(C#)中Area2D无法 teleport 到正确位置问题求助

问题描述

我刚着手开发一款小型单人2D射击游戏,其中包含枪支这类可收集物品。我制作了一把可拾取的手枪,编写代码实现玩家触碰它时将其传送至玩家手中,但功能无法正常工作。我尝试过设置不同坐标(当前测试用(0,0)),它仍会传送到远离玩家的位置。以下是代码:

using Godot;
using System;

public class Pistol : Area2D
{
    [Export] public int speed = 200;
    public Vector2 playerPosition;
    public override void _Ready()
    {
        var detect = new Character();
        playerPosition = detect.characterPosition;
        initialPosition = this.Position;
    }


    public override void _PhysicsProcess(float delta)
    {
        //* Making the pistol move
       var motion = new Vector2();
       motion.x = Input.GetActionStrength("ui_left") - Input.GetActionStrength("ui_right");
            motion.y = Input.GetActionStrength("ui_up") - Input.GetActionStrength("ui_down");
            if (Input.IsActionPressed("ui_right") || Input.IsActionPressed("ui_left"))
            {
            MoveLocalX(motion.x * speed * delta);
            }
            if (Input.IsActionPressed("ui_up") || Input.IsActionPressed("ui_down"))
            {
            MoveLocalY(motion.y * speed * delta);
            }
            
    }
    private void _on_Pistol_body_entered(object body)
    {
      this.Position =  new Vector2(0, 0);
    }
}

更新:精灵与Area2D手枪对象错位。

修复方案
  • 修正玩家对象获取逻辑:_Ready()里直接new Character()生成的是全新实例,不是场景中真实的玩家。改用节点路径或分组获取:

    public override void _Ready()
    {
        // 根据场景结构调整路径,比如玩家节点在父节点下
        Character player = GetNode<Character>("../Player");
        playerPosition = player.GlobalPosition;
        initialPosition = this.Position;
    }
    

    或者通过分组(先给玩家节点添加"player"分组):

    public override void _Ready()
    {
        foreach (Node node in GetTree().GetNodesInGroup("player"))
        {
            if (node is Character player)
            {
                playerPosition = player.GlobalPosition;
                break;
            }
        }
        initialPosition = this.Position;
    }
    
  • 解决坐标空间问题:直接设置Position = new Vector2(0,0)是全局坐标,要绑定到玩家手中,应该将手枪设为玩家的子节点,使用局部坐标:

    private void _on_Pistol_body_entered(object body)
    {
        if (body is Character player)
        {
            // 将手枪转为玩家的子节点
            Reparent(player);
            // 设置相对于玩家的局部位置(根据美术资源调整偏移)
            Position = new Vector2(30, 0);
            // 关闭碰撞监测,避免重复触发拾取
            Monitoring = false;
            // 停止手枪自身的移动逻辑
            SetProcessPhysics(false);
        }
    }
    
  • 修复精灵与Area2D错位:检查Area2D的子节点精灵的Position是否为(0,0),确保精灵锚点(Anchor)与Area2D一致。如果精灵有偏移,调整精灵的Position使其与Area2D中心对齐,或者修改Area2D的Position匹配精灵位置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 20:35:27