简体   繁体   English

如何根据运动方向旋转带有 RigidBody 的游戏对象? 团结 | 3D | C#

[英]How do I rotate a GameObject with a RigidBody based on it's movement direction? Unity | 3D | C#

The title says it all with my question.标题用我的问题说明了一切。 I am firing a projectile, for sake of ease lets call it an arrow, I'd like it to rotate so that the arrowhead is always pointing in the direction of movement.我正在发射射弹,为方便起见,我们称它为箭头,我希望它旋转,以便箭头始终指向运动方向。 So for example: if it's fired straight up it would be pointing up & when coming back down it would be facing down.因此,例如:如果它直接向上发射,它会朝上,而当它向下发射时,它会朝下。

I have searched up this question & found many different solutions, none of which have worked for me.我搜索了这个问题并找到了许多不同的解决方案,但没有一个对我有用。 A big one I see a lot is:我经常看到的一个大问题是:

transform.rotation = Quaternion.LookRotation(rigidbody.velocity); transform.rotation = Quaternion.LookRotation(rigidbody.velocity);

and this does rotate the GameObject correctly, however has weird game-breaking consequences where the game object moves slowly, jitters a lot, teleports around, then breaks completely.这确实会正确地旋转游戏对象,但是会产生奇怪的游戏破坏后果,游戏对象移动缓慢,抖动很多,四处传送,然后完全破坏。 I have tried putting this code in the Update() function, FixedUpdate() function & the LateUpdate() function all producing the same results.我尝试将此代码放入 Update() 函数、FixedUpdate() 函数和 LateUpdate() 函数中,所有这些都产生相同的结果。

https://youtu.be/L9LVM8AmjJM - link to a video showing the weird results using the code above. https://youtu.be/L9LVM8AmjJM - 链接到显示使用上述代码的奇怪结果的视频。

Try尝试

 rigidbody.MoveRotation(Quaternion.LookRotation(rigidbody.velocity));

within FixedUpdate .FixedUpdate内。

Going through transform in most cases breaks the physics and MoveRotation interpolates the rotation rather than hard jumping to it and still respects obstacles etc and interacts correctly with those.在大多数情况下,通过transform会破坏物理, MoveRotation插入旋转而不是硬跳到它,并且仍然尊重障碍物等并与它们正确交互。


What happens in your video though I think is that your velocity suddenly changes when hitting the ground -> you hard set the objects rotation -> it is kicked up into the air again because of the resulting collision forces.尽管我认为你的视频中发生了什么,但你的速度在撞击地面时突然改变 - >你硬设置物体旋转 - >由于产生的碰撞力,它再次被踢到空中。

This might of course still occure with the upper method => I would skip the rotation setting if colliding with something eg这当然可能仍然会发生在上面的方法中=>如果与某些东西发生碰撞,我会跳过旋转设置,例如

int collisions;

private void OnCollisionEnter()
{
    collisions++;
}

private void OnCollisionExit()
{
    collisions--;
}

private void FixedUpdate()
{
    if(collisions==0) rigidbody.MoveRotation(Quaternion.LookRotation(rigidbody.velocity));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM