首页 > 解决方案 > 如何使用 vanilla javascript 在画布中旋转矩形,使矩形的坐标也随旋转而变化?

问题描述

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

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

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

功能 paddleCircleColliding(圆,桨){

// 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));        

}

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

谢谢

标签: javascriptcanvasgeometrycollisionrectangles

解决方案


两种可能的方式:

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)

随便找的JS例子

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)

然后使用这些距离


推荐阅读