我在如何实施 SAT 上处于停滞状态。我完全理解它的概念并观看/阅读了许多教程,但不幸的是,我发现的所有内容要么使用库,要么使用不同的语言。我一直无法将其转换为纯 js。
到目前为止,我有我的旋转对象,我正在跟踪updateCorners()
我的 Square 类中的角。我已经使用函数为两个矩形创建了向量。我有一个用于点积的功能并将其标准化。我启动了一个函数来完成检查每个角与每个矩形的 x 和 y 向量的大部分工作,但只是不知道该去哪里。
有人会在这里写一些代码吗?我真的很感激。
let canvas = document.getElementById("canvas");
let ctx = canvas.getContext("2d");
canvas.width = 400;
canvas.height = 400;
ctx.fillStyle = 'lightgrey';
ctx.fillRect(0,0,canvas.width, canvas.height);
let mouse = {
x: null,
y: null
}
canvas.addEventListener('mousemove', e => {
mouse.x = e.x - canvas.getBoundingClientRect().x;
mouse.y = e.y - canvas.getBoundingClientRect().y;
})
class Square {
constructor(x, y, w, h, c) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.c = c;
this.a = 0;
this.r = this.a * (Math.PI/180);
this.cx = this.x + this.w/2;
this.cy = this.y + this.h/2;
this.tl = {x: 0, y: 0}; //used to track corners
this.tr = {x: 0, y: 0};
this.br = {x: 0, y: 0};
this.bl = {x: 0, y: 0};
}
draw() {
ctx.save();
ctx.translate(this.x, this.y)
ctx.rotate(this.r);
ctx.fillStyle = this.c;
ctx.fillRect(-this.w/2,-this.h/2,this.w,this.h);
ctx.restore();
}
updateCorners() {
this.a += 0.1
this.r = this.a * (Math.PI/180);
let cos = Math.cos(this.r);
let sin = Math.sin(this.r)
//updates Top Left Corner
this.tl.x = (this.x-this.cx)*cos - (this.y-this.cy)*sin+(this.cx-this.w/2);
this.tl.y = (this.x-this.cx)*sin + (this.y-this.cy)*cos+(this.cy-this.w/2)
//updates Top Right Corner
this.tr.x = ((this.x+this.w)-this.cx)*cos - (this.y-this.cy)*sin+(this.cx-this.w/2)
this.tr.y = ((this.x+this.w)-this.cx)*sin + (this.y-this.cy)*cos+(this.cy-this.w/2)
//updates Bottom Right Corner
this.br.x = ((this.x+this.w)-this.cx)*cos - ((this.y+this.h)-this.cy)*sin+(this.cx-this.w/2)
this.br.y = ((this.x+this.w)-this.cx)*sin + ((this.y+this.h)-this.cy)*cos+(this.cy-this.w/2)
//updates Bottom Left Corner
this.bl.x = (this.x-this.cx)*cos - ((this.y+this.h)-this.cy)*sin+(this.cx-this.w/2)
this.bl.y = (this.x-this.cx)*sin + ((this.y+this.h)-this.cy)*cos+(this.cy-this.w/2)
}
}
let square = new Square(150,150, 50, 50, 'red');
let square2 = new Square(175,210, 100, 50, 'blue');
function createVec(p0, p1) {
return {
x: p1.x - p0.x,
y: p1.y - p0.y
};
}
function dotProduct(v0, v1) {
return v0.x*v1.x + v0.y*v1.y;
}
function normalize(v) {
let m = Math.sqrt(v.x*v.x + v.y*v.y)
return {
x: v.x / m,
y: v.y / m
};
}
function checkIntersect(obj1, obj2) {
let obj1V1 = createVec(obj1.tr, obj1.tl);
let obj1V2 = createVec(obj1.bl, obj1.tl);
let obj2V1 = createVec(obj2.tr, obj2.tl);
let obj2V2 = createVec(obj2.bl, obj2.tl);
console.log(obj1V1)
//completly lost at this point
}
function animate() {
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.fillStyle = 'black';
ctx.fillText('x: '+mouse.x+',y: '+mouse.y, 50, 50);
square.draw();
square.updateCorners();
square2.draw();
square2.updateCorners();
requestAnimationFrame(animate)
}
animate();
<canvas id="canvas"></canvas>