I'm developing a kind of perspective based 2d/3d game in javascript.
I've got an X- and an Y-axis like I've displayed in the image below.
To my question: I've got a bunch of objects (marked with "1" and "2") on my map with properties like:
In the image Object "1" does get the coordinates x:3, y:2, and the Object "2" does get the coordinates x:5, y:4. SizeX and sizeY is w:1, h:1 for both objects.
What I'd like to do with this info is to sort all of the objects in ascending order (based on the objects position and size) to know in 3d which objects comes for another object to lateron draw all of my objects sorted into my canvas (objects in foreground/background = "layers").

Note: The Camera has to fixed position - lets say the camera has the identical X and Y value so that the camera position must not be used while calculation CameraX = CameraY.
What I've 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: first Object drawn first, second Object drawn second and so on...
Edit to the snippet above:
I've tried to sort the objects based on their x/y coordinate but it seems like the width and height parameter must be used also while calculation to avoid errors.
How do I have to make use of width/height? Tbh I've got no clue so any help would be really appreciated.
I'm not sure what you meant by:
Note: The Camera has to fixed position - lets say the camera has the identical X and Y value so that the camera position must not be used while calculation CameraX = CameraY.
So here's a general-case solution.
You must sort the objects by their closest distance to the camera. This depends on an object's dimensions as well as its relative position.
The algorithm can be implemented in JS as follows:
// If e.g. horizontal distance > width / 2, subtract width / 2; same for vertical
let distClamp = (dim, diff) => {
let dist = Math.abs(diff);
return (dist > 0.5 * dim) ? (dist - 0.5 * dim) : dist;
}
// Closest distance to the camera
let closestDistance = (obj, cam) => {
let dx = distClamp(obj.width, obj.x - cam.x);
let dy = distClamp(obj.height, obj.y - cam.y);
return Math.sqrt(dx * dx + dy * dy);
}
// Sort using this as the metric
let sortObject = (objects, camera) => {
return objects.sort((a, b) => {
return closestDistance(a, camera) - closestDistance(b, camera);
});
}
EDIT this solution also does not work because it makes naive assumptions, will update soon or delete.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With