c# - 沿 Unity 中移动的方向旋转对象

标签 c# unity3d 2d

我有一个 2D 对象,它简单地向前移动直到它撞到另一个对象,其中物理 Material 导致该对象从另一个对象反弹。

我不是最擅长绘图的,但这是我想要它做的事情的说明:(球体中的箭头表示球体当前面向的方向)

enter image description here

enter image description here

我把它的物理部分写得很好,但是物理 Material 不会旋转游戏对象,所以实际结果看起来更像这样:

enter image description here

我知道您可以使用变换很容易地设置对象的旋转,但是如何获取游戏对象的移动方向,然后将旋转设置为该方向?

最佳答案

首先,你需要知道图像的局部方向应该指向运动的方向。这取决于您的设置,并且问题不包含足够的信息来准确了解。它可能是 Vector3.upVector3.right。当然,世界方向是通过速度得知的。

Vector3 worldDirectionToPointForward = rb2d.velocity.normalized;
Vector3 localDirectionToPointForward = Vector3.right;

然后,您想要围绕 z 轴旋转 Sprite ,使局部方向指向该方向。您可以使用 transform.TransformDirection 找到球“指向”的当前方向,然后使用 Vector3.SignedAngle 计算角度:

Vector3 currentWorldForwardDirection = transform.TransformDirection(
        localDirectionToPointForward);
float angleDiff = Vector3.SignedAngle(currentWorldForwardDirection, 
        worldDirectionToPointForward, Vector3.forward);

然后,使用 transform.Rotate 将它绕 z 轴旋转该量。

transform.Rotate(Vector3.forward, angleDiff);

我会在与墙壁发生碰撞后这样做。另一种方法是将它放在 LateUpdate 中,尽管这可能会干扰其他单一行为中发生在 LateUpdate 中的其他事情。但是,LateUpdate 方法最容易演示,因此我将在此处进行演示:

void LateUpdate()
{
    Vector3 worldDirectionToPointForward = rb2d.velocity.normalized;
    Vector3 localDirectionToPointForward = Vector3.right;

    Vector3 currentWorldForwardDirection = transform.TransformDirection(
            localDirectionToPointForward);
    float angleDiff = Vector3.SignedAngle(currentWorldForwardDirection, 
            worldDirectionToPointForward, Vector3.forward);

    transform.Rotate(Vector3.forward, angleDiff, Space.World);
}

关于c# - 沿 Unity 中移动的方向旋转对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61602909/

相关文章:

c# - C# 中 Open/SaveFileDialog 中的应用程序链接项

unity3d - 如何使 2D 碰撞器随它们绑定(bind)到的 UI 元素缩放?

2d 游戏 : fire at a moving target by predicting intersection of projectile and unit

c# - 如何在 MySQL 数据库中保存印地语字符

C# 中来自 SQL Server 的 JavaScript 数组数据

c# - 如何在鼠标位置生成对象?

c# - Unity - 如何让两个相同的游戏对象发生碰撞、相互破坏并在目标位置生成一个新的游戏对象?

java - OpenGL 的理想显示同步速率

c - 强制 MuPDF 也绘制页面背景

c# - 异常 "String was not recognized as a valid DateTime"