[英]Orbiting body constantly spinning while over southern hemisphere
我试图让我的身体独自绕地球行走,但是当身体到达地球“下半球”时会出现问题。
每当身体到达那里时,它就会像疯了似的旋转,直到身体移回到行星的“上”半球时才会停止。
吸引
public class Attractor : MonoBehaviour
{
[SerializeField] private float _gravity = -10;
public void Attract(Body body)
{
Vector3 targetDir = (body.transform.position - transform.position).normalized;
Vector3 bodyUp = body.transform.up;
body.transform.rotation *= Quaternion.FromToRotation(bodyUp, targetDir);
body.GetComponent<Rigidbody>().AddForce(targetDir * _gravity);
}
}
身体
public class Body : MonoBehaviour
{
[SerializeField] private Attractor _curAttractor;
private Rigidbody _rb;
private void Awake()
{
_rb = GetComponent<Rigidbody>();
_rb.useGravity = false;
_rb.constraints = RigidbodyConstraints.FreezeRotation;
}
private void FixedUpdate()
{
_curAttractor.Attract(this);
}
}
PathFollower
public class PathFollower : MonoBehaviour
{
[SerializeField] private float _moveSpeed;
[SerializeField] private float _reach;
private Path _curPath;
private Rigidbody _rb;
private void Awake()
{
_rb = GetComponent<Rigidbody>();
}
public void FollowPath(Path p)
{
StopAllCoroutines();
_curPath = p;
StartCoroutine(FollowCtn());
}
private IEnumerator FollowCtn()
{
int i = 0;
Vector3 target;
while (i < _curPath.Nodes.Length)
{
target = PathfindingData.NodeToWorldPosition(_curPath.Nodes[i]);
Vector3 dir;
while (Vector3.Distance(transform.position, target) > _reach)
{
dir = target - transform.position;
dir.Normalize();
_rb.MovePosition(_rb.position + dir * _moveSpeed * Time.deltaTime);
yield return null;
}
i++;
}
_rb.velocity = Vector3.zero;
_curPath = null;
}
}
关于什么可能导致这种奇怪行为的任何想法?
我的意思是疯狂旋转:
当您只关注一个轴指向的位置时, FromToRotation
最好,因为它会以任何方式改变其他轴的方向,从而最大程度地减小两次旋转之间的角度。 换句话说, FromToRotation
将更改对象的偏航角,如果这样做会减少俯仰或横滚所需的更改。
因为您担心转换的up
(总是指向远离吸引子)和forward
(在FixedUpdate
调用之间尽可能少地更改),所以最好使用另一条路由。
使用Vector3.OrthoNormalize
和Quaternion.LookRotation
将targetDir
方向指定为向上,并保持物体的transform.forward
尽可能不变(如果它们是共线的,则使用forward
的任意方向):
Vector3 targetDir = (body.transform.position - transform.position).normalized;
Vector3 bodyForward = body.transform.forward;
Vector3.OrthoNormalize(ref targetDir, ref bodyForward);
body.transform.rotation = Quaternion.LookRotation(bodyForward, targetDir);
body.GetComponent<Rigidbody>().AddForce(targetDir * _gravity);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.