gpt4 book ai didi

c# - Unity 中的 3D 物理 compass (处理旋转)

转载 作者:行者123 更新时间:2023-12-02 11:11:02 24 4
gpt4 key购买 nike

在 Unity 中寻求旋转方面的帮助,我有一个手持式 3D compass ,并且我的手指向“北”,这是一个空变换。我试图锁定手的旋转,这样当 compass 倾斜时,手仍然可以准确地寻找北方。

问题是,当倾斜时,手会从 compass 中弹出。

这是我迄今为止拥有的以下代码以及下面问题的图片。

public Transform target;
public Transform housing;
public float speed = 1.0f;

// Start is called before the first frame update
void Start()
{

}

// Update is called once per frame
void Update()
{
var lookPos = target.position - transform.position; // assumes this script is attached to the needle
var housingLocal = housing.InverseTransformPoint(lookPos); // change of coordinates from world space to housing space
var localProjection = new Vector3(housingLocal.x, 0, housingLocal.z); // Remove the vertical offset so that we will look along the plane of the housing
var worldProjection = housing.TransformPoint(localProjection); // change of coordinates back into world space

var rotation = Quaternion.LookRotation(worldProjection);
transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * speed);
}

enter image description here

最佳答案

手本身的变形可以吗?不管怎样,我假设手的transform.up向量与手对齐(就像Unity中Cylinder的基元一样,你可以使用一个空对象作为父亲来修复这个问题)。

在这种情况下,这段代码应该可以工作:

void Update()
{
Vector3 lookPos = target.position - transform.position;
transform.up = Vector3.Slerp(transform.up, lookPos, Time.deltaTime * speed);
}

有了这个,你的 compass 指针将始终顺利地指向你的北方点。如果不是绝对必要的话,我建议您避免使用四元数,我总是更喜欢通过变换正交向量(右、上、前)进行旋转。

关于c# - Unity 中的 3D 物理 compass (处理旋转),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59663324/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com