【问题标题】:Sphere to Block - Corner Collision Detection (JS)Sphere to Block - 角碰撞检测 (JS)
【发布时间】:2018-04-10 06:47:26
【问题描述】:

我做了一个小引擎/游戏。它关于物理和碰撞一切似乎都很好,唯一我不知道如何实现这一点:

如何使球体正确地从拐角处反弹?

我只为每个方块的所有 4 个面进行了碰撞检测,但这让游戏变得如此困难,因为当球体撞击角落时,它也会在 X 轴上获得速度。

让球体落在一个方块的边缘试试这个,它 将滑到一边并保持其下降方向。

The Game is on CodePen

Just in Case you want to make your own Level

Check CodePen :)

【问题讨论】:

    标签: javascript html canvas collision rigid-bodies


    【解决方案1】:

    找到圆与角接触点后的解决方案

    定义问题。放 ?符合你的价值观

    const corner  = {x : ?, y : ?};
    const ball = {
        x : ?,   // ball center
        y : ?,
        dx : ?,  // deltas (the speed and direction the ball is moving on contact)
        dy : ?,
    }
    

    还有图片来帮助可视化

    步骤是

    // get line from ball center to corner
    const v1x = ball.x - corner.x;  // green line to corner
    const v1y = ball.x - corner.x;
    
    // normalize the line and rotate 90deg to get the tangent
    const len = (v1x ** 2 + v1y ** 2) ** 0.5;
    const tx = -v1y / len;  // green line as tangent
    const ty =  v1x / len;
    
    // Get the dot product of the balls deltas and the tangent
    // and double it (the dot product represents the distance the balls
    // previous distance was away from the line v1, we double it so we get 
    // the distance along the tangent to the other side of the line V1)
    const dot = (ball.dx * tx + ball.dy * ty) * 2; // length of orange line
    
    // reverse the delta and move dot distance parallel to the tangent
    // to find the new ball delta.
    ball.dx = -ball.dx + tx * dot; // outgoing delta (red)
    ball.dy = -ball.dy + ty * dot;
    

    【讨论】:

      猜你喜欢
      • 2011-03-15
      • 1970-01-01
      • 1970-01-01
      • 2013-02-21
      • 1970-01-01
      • 1970-01-01
      • 2016-06-10
      • 2014-06-09
      • 2011-10-06
      相关资源
      最近更新 更多