Unity:围绕玩家的 3D 自上而下旋转项目

Unity: 3D top-down rotate item around player

我正在尝试让一个对象从自上而下的角度始终位于玩家的“前面”。这是演示我正在尝试做的事情的屏幕截图。

所以你可以看到,当蓝色胶囊(玩家)拿起绿色胶囊(物品)时,物品正确地悬停在玩家面前(由 z 轴蓝色箭头指示),但是当玩家转向任何其他方向,物品不会跟随,而是相对于玩家保持在完全相同的位置。

我的播放器控制器脚本如下所示:

using UnityEngine;

public class PlayerController : MonoBehaviour {

  public float movementSpeed = 10;

  private Rigidbody body;
  private Vector2 movement;

  void Start() {
    body = GetComponent<Rigidbody>();
  }

  void Update() {
    movement.x = Input.GetAxis("Horizontal");
    movement.y = Input.GetAxis("Vertical");
  }

  void FixedUpdate() {
    body.velocity = new Vector3(movement.x * movementSpeed * Time.deltaTime, 0, movement.y * movementSpeed * Time.deltaTime);

    // this is what updates the direction of the blue arrow in the direction of player movement
    if(movement.x != 0 || movement.y != 0) {
      body.rotation = Quaternion.LookRotation(body.velocity);
    }
  }
}

这是我的拾取脚本(应该更新物品的位置):

using UnityEngine;

public class Pickup : MonoBehaviour {

  private GameObject item;
  public float carryDistance = 1;

  void OnCollisionEnter(Collision collision) {
    if(collision.gameObject.CompareTag("Item")) {
      item = collision.gameObject;
    }
  }

  void Update() {
    if(item) {
      item.transform.position = transform.position + new Vector3(0, 0, carryDistance);
    }
  }
}

所以重申我的问题:如何更新项目的位置,使其始终悬停在蓝色箭头一侧的玩家旁边?

您可以通过使用播放器来实现此目的transform.forward

item.transform.position = transform.position + (transform.forward * carryDistance) 
+ (Vector3.up * carryHeight);

或者,您可以只向玩家添加空 子游戏对象 ,将其放置在玩家面前,并使用其变换位置和旋转来定位拾取的对象。

public class Pickup : MonoBehaviour {

  public Transform pickupPositionTransform;
  private GameObject item;
  public float carryDistance = 1;

  void OnCollisionEnter(Collision collision) {
    if(collision.gameObject.CompareTag("Item")) {
      item = collision.gameObject;
    }
  }

  void Update() {
    if(item) {
      item.transform.position = pickupPositionTransform.position;
      item.transform.rotation = pickupPositionTransform.rotation;
    }
  }
}