c# - 插值对象碰撞卡住

标签 c# collision-detection interpolation unity3d

我正在 Unity 2D 中进行非常基本的测试。我遇到的问题是,当我的 Sprite 与地面碰撞时,它会不断地检查事件,几乎太频繁了,所以 Sprite 一直处于不确定状态。它没有机会离开地面,因为当它执行检查时告诉它转身导致它快速上下移动。 如下图所示:

https://m.youtube.com/watch?v=gPmmLjGe9iQ

我想要的是当接触发生时 Sprite 需要改变它的 Y 轴方向。请在下面查看我的代码。

void Update () {
    hitWall = Physics2D.OverlapCircle(wallCheckUp.position, wallCheckRadius, whatIsWall);
    if (hitWall)
    {
        moveUp = !moveUp;
    }

    if (moveUp)
    {
        transform.localScale = new Vector3(-1f, 1f, 1f);
        GetComponent<Rigidbody2D>().velocity = new Vector2(speed, GetComponent<Rigidbody2D>().velocity.x);
    }
    else
    {
        transform.localScale = new Vector3(1f, 1f, 1f);
        GetComponent<Rigidbody2D>().velocity = new Vector2(-speed, GetComponent<Rigidbody2D>().velocity.x);
    }
}

如果需要更多信息,请告诉我。

编辑

为了让我更清楚,请查看我的 Sprite 设置。

enter image description here

最佳答案

OverlapCircle 检查是否有任何重叠,因此只要它与对象之间存在重叠,它就会为真,因此对每一帧运行 if 语句以确认它为真。尝试使用 OnCollisonEnter2D 或 OnTriggerEnter2D 方法(只需替换方法名称):

void OnCollisionEnter2D(Collision2D coll)
{
    moveUp = !moveUp;
    if (moveUp)
    {
        transform.localScale = new Vector3(-1f, 1f, 1f);
        GetComponent<Rigidbody2D>().velocity = new Vector2(speed,  GetComponent<Rigidbody2D>().velocity.y);
    }
    else
    {
        transform.localScale = new Vector3(1f, 1f, 1f);
        GetComponent<Rigidbody2D>().velocity = new Vector2(-speed, GetComponent<Rigidbody2D>().velocity.y);
    }
}

还要确保每个对象在检查器中都有一个 Collider2D。

还有一件事。初始化 Vector2 时,参数的顺序是 x,y。我注意到在您的代码中,您在 y(垂直)组件的参数中使用了 GetComponent().velocity.x(水平)。如果您的 Sprite 上下移动,那么这可能是您出错的原因,因为它的 y 分量没有改变(除非您有一些其他代码可以改变 x 分量)。

所以你想改变

new vector2(speed[-speed], GetComponent<Rigidbody2d>().velocity.x)

new vector2(GetComponent<Rigidbody2d>().velocity.x, speed[-speed])

希望这对您有所帮助。

关于c# - 插值对象碰撞卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42114402/

相关文章:

c# - for 循环如何与堆栈溢出相关?

c# - 当一个构造函数实现另一个构造函数时有好处还是坏处?

Java - 形状碰撞检测

image-processing - 成像插值 - 创建中间图像?

Angular 6 我的插值属性在 API 中更新后未在 UI 中更新

c# - session 未在页面之间传递c#

c# - asmx 返回值中的空属性

OpenGL GL_SELECT 或手动碰撞检测?

c# - 玩家到体素碰撞检测/响应

javascript - 三 Angular 测量 + 线性插值 + 3D 投影的毛刺