Capped Center
by wio_dude
HTML
<canvas id="canvas" width="500" height="500"></canvas>
<div>
Stage object is red, with a black circle as the max distance.
Camera position is orange and will not move outside the max distance.
Players are blue.
The centroid is green.
If the centroid given equal weight to the players, the result is lightgreen.
Camera will be in the direction of the centroid, but not further than the max radius.
</div>
<div>
Controls
<ul>
<li>1 - move player 1 to mouse position</li>
<li>2 - move player 2 to mouse position</li>
<li>Q - show/hide player 2</li>
<li>WASD - moves player 1</li>
<li>Arrow Keys - moves player 2</li>
</ul>
</div>
CSS
#canvas {
border: 1px solid black;
}
JavaScript
const TAU = 2 * Math.PI;
let mousePosition = [0, 0];
let dragObject = null;
let keysReleased = {};
const keysDown = {};
const canvas = document.getElementById('canvas');
const context = canvas.getContext('2d');
const MAX_DISTANCE = 50;
const WIDTH = 500;
const HEIGHT = 500;
const driver = {
x: 250,
y: 250,
r: 15,
color: 'red',
visible: true,
movable: true,
};
const player = {
x: 200,
y: 200,
r: 10,
color: 'blue',
visible: true,
movable: true,
};
const player2 = {
x: 200,
y: 300,
r: 10,
color: 'lightblue',
visible: true,
movable: true,
};
const centroid = {
x: 150,
y: 150,
r: 15,
color: 'green',
visible: true,
movable: false,
};
const motionAngle = {
x: 300,
y: 250,
r: 10,
color: 'lightgreen',
visible: true,
movable: false,
};
const camera = {
x: 180,
y: 180,
r: 10,
color: 'orange',
visible: true,
movable: false,
};
const objects = [
centroid, driver, player2, player, motionAngle, camera
];
document.addEventListener('mousemove', function(event) {
const rect = canvas.getBoundingClientRect();
const newPos = [
event.clientX - rect.left, event.clientY - rect.top
];
if (dragObject) {
dragObject.x += newPos[0] - mousePosition[0];
dragObject.y += newPos[1] - mousePosition[1];
}
mousePosition = newPos;
});
canvas.addEventListener('mousedown', function(event) {
for (const object of objects) {
if (object.movable) {
const dx = mousePosition[0] - object.x;
const dy = mousePosition[1] - object.y;
if (dx * dx + dy * dy < object.r * object.r) {
dragObject = object;
}
}
}
});
canvas.addEventListener('mouseup', function(event) {
dragObject = null;
});
canvas.addEventListener('mouseleave', function(event) {
dragObject = null;
});
document.addEventListener('keydown', function(event) {
keysDown[event.code] = true;
});
document.addEventListener('keyup', function(event) {
keysDown[event.code] = false;
keysReleased[event.code] =...