I'm facing an issue while trying to identify the two most extreme vertices of an object in my 2D game using JavaScript. The goal is to determine where I should create a trapezoid to simulate the shadow casting.
Currently, my approach involves rotating the object's vertices to the same plane as the light and then selecting the vertices with the highest and lowest Y values. However, this isn't working as expected, as I end up consistently selecting the diagonal vertices.
I thought about selecting the vertices with the greatest difference in angles relative to the light to determine which ones are the boundary vertices of the object, but I couldn't get it right.
Github repository: https://github.com/markvaaz/game-engine/tree/Renderer
Here's a snippet of my attempt to create the method within my LightingManager class:
/**
* Gets the extremes of the shape in relation to the plane of the angle between the light and the shape
* @param {Object} shape
* @param {Object} light
* @method getVerticesFromExtremes
*/
getVerticesFromExtremes(shape, light){
const { position: center, vertices } = shape;
const { position } = light;
const angle = new Vector(position).angleBetween(center);
let minIndex = 0;
let maxIndex = 0;
vertices.forEach((vertex, index) => {
vertex = new Vector(vertex.x, vertex.y);
vertex.rotate(-angle);
if(vertex.y < vertices[minIndex].y){
minIndex = index;
}
if(vertex.y > vertices[maxIndex].y){
maxIndex = index;
}
});
if(minIndex > maxIndex) return {
min: maxIndex,
max: minIndex
}
return {
min: minIndex,
max: maxIndex
}
}
Here's an example image illustrating the desired shadow effect achieved by selecting the two most extreme points:
For testing purposes, I'm using the following vertex coordinates for a rectangle:
[ { "x": -32, "y": -41 }, { "x": 32, "y": -41 }, { "x": 32, "y": 41 }, { "x": -32, "y": 41 } ]
Note that the coordinates belong to the shape, and the global position is not included. The shape's global position is indicated by the 'position' property of the shape. The light position is its global position
This is the light object and its properties:
{
"enabled": true,
"mode": "lighter",
"brightness": 1,
"radius": 250,
"type": "cone",
"position": {
"x": 722.5,
"y": 413.9
},
"steps": [
{
"start": 1,
"color": "rgba(255, 255, 255, 0.8)"
},
{
"start": 0,
"color": "transparent"
}
],
"angle": 0.0006666665679014124,
"distance": 150.0000333333296
}
EDIT: DMGregory's answer works up to a certain distance from the object; however, upon getting closer, it ends up selecting the wrong vertex.


