javascript - 如何使用 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));
}
当我在没有使用上面给出的旋转函数旋转矩形的情况下测试它时,它就像一个魅力,但是当我旋转表面并测试碰撞检测时,球似乎与矩形曾经所在的不可见表面发生碰撞。
谢谢
解决方案
两种可能的方式:
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)
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)
然后使用这些距离
推荐阅读
- sql - 如何在更新语句时在表中动态添加数据库名称
- vb.net - VB.net不同线程之间的通信
- postgresql - Postgres 11 - 如何将函数从一个模式复制到另一个模式
- ios - 有没有办法让 TextInput 表现得像一个按钮,即能够被选中(onPress)?
- ios - 启动 Quickblox 视频通话从 Web 到 iOS 应用程序后立即应用程序崩溃
- unicode - Imagemagick 将复合字母显示为拆分
- flutter - Flutter Radial Select Menu (Pie Menu) Implementation
- visual-studio-code - 如何从 VSCode 中的 textmate 范围中删除样式
- c# - 在 C# SerializeObject 中自定义 JSON 键名
- angular - 忽略角通用`renderModule``extraProviders`