【问题标题】:Unity prefab movementunity prefab 运动
【发布时间】:2018-06-21 19:32:17
【问题描述】:

您好,我想在我的游戏中跟随玩家创建一组相同的预制件。我已经有了跟随播放器的预制件,但是当有多个播放器时,它们只会沿着完全相同的路径相互叠加。有没有一种方法可以让他们跟随玩家但表现得像一群蜜蜂一样移动? 谢谢!

这是我预制件上的脚本:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class KillerMovement : MonoBehaviour {


    public GameObject player;


    void FixedUpdate()
    {
        Vector2 toTarget = player.transform.position - transform.position;
        float speed = 0.5f;

        transform.Translate(toTarget * speed * Time.deltaTime);
    }
}

【问题讨论】:

  • 你有这个脚本单独附加到每个预制件上吗?还是仅附加到父组件。如果是单独依附的,只要起始位置不同,都应该走自己的路

标签: c# unity3d


【解决方案1】:

最佳解决方案取决于您的游戏逻辑,但您可能会考虑在开始跟随之前有一个延迟(您可以根据您希望特定对象在跟踪中的位置来调整延迟。

using System.Collections;
using UnityEngine;

public class Follower : MonoBehaviour
{
  public GameObject player;
  public float delay = 0f;
  public float speed = .5f;
  bool isReady = false;

  void Start()
  {
    StartFollowing();
  }

  public void StartFollowing()
  {
    StartCoroutine(WaitThenFollow(delay));
  }

  IEnumerator WaitThenFollow(float delay)
  {
    yield return new WaitForSeconds(delay);
    isReady = true;
    Debug.Log(gameObject.name);
    Debug.Log(Time.time);
  }

  void FixedUpdate()
  {
    if (isReady && player != null)
    {
      Vector2 toTarget = player.transform.position - transform.position;
      transform.Translate(toTarget * speed * Time.deltaTime);
    }
  }
}

我在 Start 方法中调用了 StartFollowing 来测试代码。您应该在游戏逻辑适当时调用此方法。

【讨论】:

    猜你喜欢
    • 2019-10-22
    • 1970-01-01
    • 1970-01-01
    • 2014-10-12
    • 2019-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多