I am currently working on a unique perspective-based 2D/3D game using javascript.
In the image below, you can see the X and Y-axis that I have implemented for this project.
My question: On the map, I have several objects labeled as "1" and "2" with properties such as:
- positionX / positionY
- sizeX / sizeY
Object "1" is located at coordinates x:3, y:2
, while Object "2" is at x:5, y:4
. Both objects have a size of w:1, h:1
.
My goal is to sort these objects in ascending order based on their positions and sizes, so that in the 3D view, I know which objects come in front of others. This will help me draw all objects in the correct order on the canvas, creating layers in the foreground and background.
https://i.sstatic.net/c6Zw6.png
Note: The camera has a fixed position, meaning the X and Y values of the camera are identical. Therefore, the camera position must not be factored in while calculating CameraX = CameraY
.
This is what I have tried so far:
let objects = [
{
name: "objectA",
x: 8,
y: 12,
w: 2,
h: 2
},
{
name: "objectB",
x: 3,
y: 5,
w: 2,
h: 2
},
{
name: "objectC",
x: 6,
y: 2,
w: 1,
h: 3
}
]
let sortObjects = (objects) => {
return objects.sort((a, b)=> {
let distanceA = Math.sqrt(a.x**2 + a.y**2);
let distanceB = Math.sqrt(b.x**2 + b.y**2);
return distanceA - distanceB;
});
}
let sortedObjects = sortObjects(objects);
console.log(sortedObjects);
// NOTE in 3d: objects are drawn in the order they appear in the sorted array...
Edit to the snippet above:
I attempted to sort the objects based on their x/y coordinates, but it seems that the width and height parameters also need to be considered to avoid errors.
How should I incorporate width/height into the calculations? I am unsure about this aspect, so any guidance would be greatly appreciated.