gpt4 book ai didi

javascript - 等距 3D 碰撞检测

转载 作者:行者123 更新时间:2023-11-28 04:15:44 25 4
gpt4 key购买 nike

我正在为游戏制作等距 map ,我可以绘制它,但我不知道如何在没有 Threejs 或其他 3d 库的情况下实现某种 3d 碰撞检测。

有可能吗?也许将 block 变成对象可以有所帮助?我已经搜索过,但只找到了库。

这是我的 JavaScript 代码:

var canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d'),
width = canvas.width = window.innerWidth,
height = canvas.height = window.innerHeight,
stop = false;

var tw, th;
var player;

setup();
draw();

function setup(){
ctx.translate(width/2,50);

tw = 60; //tile width
th = 30; // tile height
player = new Player(2,3,3);

};

function draw(){

ctx.clearRect(-width/2,-50,width*1.5,height+50);

for(var i = 0; i < 5; i++){
for(var j = 0; j < 5; j++){
drawBlock(i,j,1,tw,th);
}
}

if(!stop){
requestAnimationFrame(draw);
}
}

function drawBlock(x,y,z,w,h){

var top = "#eeeeee",
right = '#cccccc',
left = '#999999';

ctx.save();
ctx.translate((x-y)*w/2,(x+y)*h/2);

ctx.beginPath();
ctx.moveTo(0,-z*h);
ctx.lineTo(w/2,h/2-z*h);
ctx.lineTo(0,h-z*h);
ctx.lineTo(-w/2,h/2-z*h);
ctx.closePath();
ctx.fillStyle = "black";
ctx.stroke();
ctx.fillStyle = top;
ctx.fill();

ctx.beginPath();
ctx.moveTo(-w/2,h/2-z*h);
ctx.lineTo(0,h-z*h);
ctx.lineTo(0,h);
ctx.lineTo(0,h);
ctx.lineTo(-w/2,h/2);
ctx.closePath();
ctx.fillStyle = "black";
ctx.stroke();
ctx.fillStyle = left;
ctx.fill();

ctx.beginPath();
ctx.moveTo(w/2,h/2-z*h);
ctx.lineTo(0,h-z*h);
ctx.lineTo(0,h);
ctx.lineTo(0,h);
ctx.lineTo(w/2,h/2);
ctx.closePath();
ctx.fillStyle = "black";
ctx.stroke();
ctx.fillStyle = right;
ctx.fill();

ctx.restore();

}

function drawTile(x,y,stroke,col){

ctx.save();
ctx.translate((x-y)*tw/2,(x+y)*th/2);

ctx.beginPath();
ctx.moveTo(0,0);
ctx.lineTo(tw/2,th/2);
ctx.lineTo(0,th);
ctx.lineTo(-tw/2,th/2);
ctx.closePath();
if(stroke){
ctx.stroke();
}else{
ctx.fillStyle = col;
ctx.fill();
}

ctx.restore();

}

function Player(x,y,z){
this.x = x;
this.y = y;
this.z = z;
this.w = 10; //width
this.h = 10; //height
}
canvas{
width:100%;
height:100%;
}
<canvas id="canvas"></canvas>

最佳答案

你追求的是立方体碰撞。我通过谷歌搜索得到的第一个结果是 MDN 上一篇名为 3D collision detection 的文章:

Mathematically this would look like so:

f(A,B) = (AminX <= BmaxX ∧ AmaxX >= BminX) ∧ (AminY <= BmaxY ∧ AmaxY >= BminY) ∧ (AminZ <= BmaxZ ∧ AmaxZ >= BminZ)

And in JavaScript, we'd use this:

function intersect(a, b) {
return (a.minX <= b.maxX && a.maxX >= b.minX) &&
(a.minY <= b.maxY && a.maxY >= b.minY) &&
(a.minZ <= b.maxZ && a.maxZ >= b.minZ);
}

关于javascript - 等距 3D 碰撞检测,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45869786/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com