如何解决Unity:围绕玩家自上而下的 3D 旋转项目
我试图从自上而下的角度让物体始终位于玩家“前面”。下面的屏幕截图展示了我正在尝试做的事情。
如您所见,当蓝色胶囊(玩家)拿起绿色胶囊(物品)时,该物品正确悬停在玩家面前(由 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,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,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;
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。