首页 > 解决方案 > Unity - 像声波一样运行循环而不会摔倒

问题描述

我正在为一个自由职业者制作这个 2D 平台游戏,我必须做一个声音机制,我必须让角色通过一个完整的循环而不摔倒,我意识到要这样做首先我必须旋转角色符合他穿过循环,但第二部分是我卡住的地方。

所以,基本上,我怎样才能让角色在不摔倒的情况下循环运行。

private void OnCollisionEnter2D(Collision2D coll)
{
    Vector3 collRotation = coll.transform.rotation.eulerAngles;

    if (coll.gameObject.tag == "Ground")
    {
    //in this part i rotate the player as he runs through the loop
        transform.eulerAngles = new Vector3(transform.eulerAngles.x, transform.eulerAngles.y, collRotation.z);

        //this is the part that i am stuck, trying to figure out how to make the character stay in the loop without falling, i tried collision detection,
    //i tried raycasting but nothing seems to work
        if (IsGrounded)
        {
            GetComponent<Rigidbody2D>().AddForce(Vector2.down, ForceMode2D.Impulse);
        }
    }
}

标签: c#unity3d2dgame-physicsgame-development

解决方案


最常用于重制和类似的技巧是在进入时获得玩家角色的速度。

// Feel free to adjust this to whatever works for your project.
const float minimumAttachSpeed = 2f;

// This should be your characters current movement speed
float currentSpeed;

// You need a Rigidbody in this example, or you can just disable
// any custom gravity solution you may have created
Rigidbody2D rb;

如果角色的速度超过了最低附着速度,那么您可以让他们以该速度遵循预定义的路径。

bool LoopAttachmentCheck()
{
    return minimumAttachSpeed <= currentSpeed;
}

现在您可以检查自己是否移动得足够快!我假设在这个例子中你使用的是Rigidbody2D ...

(此检查仅应在您进入或当前在循环中时运行)

void Update()
{
    if( LoopAttachmentCheck() )
    {
        // We enable this to prevent the character from falling
        rb.isKinematic = true;

        // Here you write the code that allows the character to move
        // in a circle, e.g. via a bezier curve, at the currentSpeed.
    }
    else
    {
        rb.isKinematic = false;
    }
}

由您来实现实际的旋转行为。如果我是你,一个很好的方法是(假设它是一个完美的圆)从圆的中心使用RotateAround

如果您有更复杂的形状,您可以使用航路点进行移动,并以您的速度遍历它们。

一旦你跟不上速度,你的角色就会掉下来(例如,如果玩家决定停止跑步)并且 Rigibody2D 将变得运动。

希望这可以帮助!


推荐阅读