【问题标题】:How do I rotate a rectangle in the canvas using vanilla javascript in such a way that the coordianates of the rectangle also change with the rotation?如何使用 vanilla javascript 在画布中旋转矩形,使矩形的坐标也随旋转而变化?
【发布时间】:2019-07-25 21:25:14
【问题描述】:

我正在尝试使用圆心之间的距离来检测圆和矩形之间的碰撞。碰撞检测一直工作正常,除非我检测到圆形与旋转矩形的碰撞。圆与矩形的宝贵位置发生碰撞。我希望它与新旋转的矩形发生碰撞。

我正在使用 rotate() 函数和 Math.PI(angle * Math.PI/180)

这是我用来检测碰撞的代码:

function paddleCircleColliding(circle, paddle) {

// this is the distance btw the center of the ball and the center of the any rectangle
let distX = Math.abs(circle.x - paddle.x - paddle.w / 2);
let distY = Math.abs(circle.y - paddle.y - paddle.h / 2);

// this compares the distance with the sum of half the width of the rectangle and the radius of the circle
if (distX > (paddle.w / 2 + circle.r)) {
    return false;
}
if (distY > (paddle.h / 2 + circle.r)) {
    return false;
}

// this compares the distance with half the width of the rectangle  
if (distX <= (paddle.w / 2)) {
    return true;
}
// this compares the distance with half the height of the rectangle
if (distY <= (paddle.h / 2)) {
    return true;
}
// this is to check if the ball hits the corner of the rectangle
let dx = distX - paddle.w / 2;
let dy = distY - paddle.h / 2;
return (dx * dx + dy * dy <= (circle.r * circle.r));        

}

当我测试它而不使用上面给出的旋转函数旋转矩形时,它就像一个魅力,但是当我旋转表面并测试碰撞检测时,球似乎与矩形曾经所在的不可见表面发生碰撞。

谢谢

【问题讨论】:

  • 嗨,欢迎来到 StackOverflow!我认为你应该展示你的这个三角形和碰撞的实现到底是什么样子的,因为现在猜测太多了。

标签: javascript canvas geometry collision rectangles


【解决方案1】:

两种可能的方式:

1) 在由矩形定义的旋转坐标系中获取圆心坐标并使用已知方法。坐标变换,计算(Fi为旋转角度)

tx = circle.x - rectanglecenter.x
ty = circle.y - rectanglecenter.y
cx = rectanglecenter.x + tx * Cos(Fi) + ty * Sin(Fi)
cy = rectanglecenter.y - tx * Sin(Fi) + ty * Cos(Fi)

Arbitrary found JS example

2) 使用标量积计算向量CR=circle-rectanglecenter 到方向向量的投影长度,其中分量是(Cos(Fi), Sin(Fi))(-Sin(Fi), Cos(Fi))

distX' = Abs(Cos(Fi)*CR.x + Sin(Fi)*CR.y)
distY' = Abs(-Sin(Fi)*CR.x + Cos(Fi)*CR.y)

然后使用这些距离

【讨论】:

    猜你喜欢
    • 2012-11-27
    • 2017-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-07
    • 1970-01-01
    • 2021-05-31
    相关资源
    最近更新 更多