区域在godot (c#)中不能传送到正确的位置



我刚开始制作一款小型单人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手枪上脱臼了。

忽略你为什么要传送收集物,为什么收集物在输入时移动,以及…这是什么,但忽略所有…

Position相对于父代。所以Vector2(0, 0)是母体的位置。你想用GlobalPositions代替。

像这样:

var target = body as Spatial;
if (Object.IsInstanceValid(target))
{
this.GlobalPosition = target.GlobalPosition;
}

你可以更具体地使用玩家角色类别(假设这里称为PlayerCharacter):

var target = body as PlayerCharacter;
if (Object.IsInstanceValid(target))
{
this.GlobalPosition = target.GlobalPosition;
}

你可能想要添加一个Position2D作为玩家的孩子,这样你就可以调整枪的位置(假设它被称为"GunPosition")。所以你可以这样做:

var target = body as PlayerCharacter;
if (Object.IsInstanceValid(target))
{
this.GlobalPosition = target.GetNode<Position2D>("GunPosition").GlobalPosition;
}

最新更新