Reputation: 111
I'm making an isometric map for a game, I can draw it, but I don't know how to implement a sort of 3d collision detection without Threejs or other 3d library.
It is possible? Maybe make the block an Object can help? I have searched, but I found only libraries.
This is my JavaScript code:
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>
Upvotes: 1
Views: 394
Reputation: 2614
What you're after is cube collision. The first result I get for googling that is an article on MDN named 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); }
Upvotes: 0