Vector2.MoveTowards-移动到目标位置等等

时间:2019-02-08 18:02:13

标签: unity3d c#-4.0

我几乎创造了游戏,但是有一件事对我来说很难。我想将玩家移动到目标,还有更多。

红点是目标,但我想将玩家移到目标一点。

P.S 如果玩家向右走,那么我希望他达到目标并向右走一点

左,上,下相同

查找附件:https://imgur.com/a/RF0xIQq 红点是目标,但我希望玩家移动到目标,而其他面向目标(绿点)

我尝试过前进的步伐,但是我没有任何想法。

    void Start()
    {

    }

    void Update()
    {
        target = GameObject.FindGameObjectWithTag("Player").GetComponent<Transform>();
        transform.position = Vector2.MoveTowards(transform.position, target.position, (speed * Time.deltaTime));
    }
    //Mob have "Player" TAG (Player is not a player) |Targeting is fine|

1 个答案:

答案 0 :(得分:1)

您可以添加一个偏移值

// ajdust this in the inspector
public float offset = 0.1f;

,然后将其添加到从玩家到目标的方向上的位置。正如Foggzie所提到的,由于可能会发生一些问题,因此这可能不是可复制的代码。为了防止玩家在超越目标后转身并来回移动,可以使用setter方法仅获得一次方向:

public float offset;
public float threshold = 0.0001f;
public float speed;

private GameObject target;
private Vector3 direction;
private Vector3 targetPosition;

public void SetTarget(GameObject newTarget)
{
    target = newTarget;

    // adding the offset in that direction
    targetPosition = target.transform.position + direction * offset;

    // direction from the player to the target
    direction = (target.transform.position - transform.position).normalized;
}

private void Update()
{
    if (!target) return;

    // make Player overshoot the target by offset
    transform.position = Vector2.MoveTowards(transform.position, targetPosition, (speed * Time.deltaTime));

    // stop if target is reached
    if (Vector3.Distance(transform.position, targetPosition) <= threshold)
    {
        target = null;
    }
}

我不知道您何时以及如何更改目标,因此目前尚不将播放器的移动限制为仅像图片中的X和Y……但是您会做的例如

SetTarget(GameObject.FindGameObjectWithTag("Player").GetComponent<Transform>());

enter image description here