JSFiddle - React, Tailwind, and code Playground
HTML
<script src="//cdnjs.cloudflare.com/ajax/libs/crafty/0.5.3/crafty-min.js"></script>
<p>
The red box will follow your mouse (x and y). Scroll up and down to change the depth of it (z).
</p>
<div id="display"></div>
<div id="coords"><div/>
CSS
#display{
position:relative;
width:640px;
height:480px;
border:1px solid #000;
overflow:hidden;
}
JavaScript
var gameLoop;
var nearClippingPlane = 3;
var targetFPS = 33;
var entities = [];
var display = $('#display');
var coords = $('#coords');
$(function(){
Reset();
Start();
});
display.on('mousemove', function(e){
var offset = display.offset();
entities[0].x = e.pageX - offset.left;
entities[0].y = e.pageY - offset.top;
}).on('mousewheel DOMMouseScroll', function(e){
if(e.originalEvent.wheelDelta/120 > 0) {
entities[0].z = entities[0].z + 0.5;
}
else{
entities[0].z = entities[0].z - 0.5;
}
});
function Reset(){
entities = [];
display.empty();
CreateEntity(100, 200, 320,240,10, '#f00', function(e){
coords.text('x: ' + e.x + ' y: ' + e.y + ' z: ' + e.z);
});
Draw();
}
function Start(){
if(gameLoop)
Stop();
gameLoop = setInterval(function(){
Update();
Draw();
}, targetFPS);
}
function Stop(){
window.clearInterval(gameLoop);
}
function Update(){
// Update positions...
for(var e in entities){
entities[e].update(entities[e]);
}
}
function Draw(){
// Clear and redraw...
display.empty();
entities.sort(function(a,b){return a.z-b.z});
for(var e in entities){
//if(entities[e].z >= 0)
DrawEntity(entities[e]);
}
}
function CreateEntity(height, width, x,y,z, color, callback){
var id = entities.length;
var entity = {
id: id,
x: x,
y: y,
z: z,
height: height,
width: width,
color: color,
update: callback || function(e){}
};
entities.push(entity);
return entity;
}
function DrawEntity(entity){
var scale = DepthScale(entity.z);
var sprite = $('<div id="'+entity.id+'"></div>');
var renderHeight = (scale*entity.height);
var renderWidth = (scale*entity.width);
sprite.css({
position: 'absolute',
height: renderHeight + 'px',
...