Here's the modified code with gravity removed and shapes floating around:
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Floating Neon Shapes</title>
<!-- Matter.js CDN -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/matter-js/0.19.0/matter.min.js"></script>
<style>
body {
margin: 0;
overflow: hidden;
user-select: none;
background: #000;
}
#controls {
position: absolute;
top: 10px;
left: 10px;
z-index: 10;
background: rgba(20,20,40,0.85);
color: #0ff;
padding: 10px;
border: 1px solid #0ff;
border-radius: 4px;
box-shadow: 0 0 10px #0ff;
}
#editor {
position: absolute;
display: none;
z-index: 20;
background: rgba(20,20,40,0.95);
color: #0ff;
border: 1px solid #0ff;
padding: 10px;
border-radius: 4px;
box-shadow: 0 0 10px #0ff;
}
#editor label {
display: block;
margin-top: 5px;
}
#editor input[type="number"], #editor input[type="color"] {
background: #111;
color: #0ff;
border: 1px solid #0ff;
border-radius: 2px;
}
#editor button {
background: #0ff;
color: #111;
border: none;
border-radius: 2px;
margin-top: 8px;
margin-right: 5px;
padding: 3px 10px;
cursor: pointer;
box-shadow: 0 0 5px #0ff;
}
#editor button:hover {
background: #00e0e0;
}
select {
background: #111;
color: #0ff;
border: 1px solid #0ff;
border-radius: 2px;
margin-right: 5px;
}
button {
background: #0ff;
color: #111;
border: none;
border-radius: 2px;
padding: 3px 10px;
cursor: pointer;
box-shadow: 0 0 5px #0ff;
}
canvas {
display: block;
/* Neon glow for shape outlines */
filter: drop-shadow(0 0 8px #0ff);
}
</style>
</head>
<body>
<div id="controls">
<label for="shapeSelect">Select a shape:</label>
<select id="shapeSelect">
<option value="rectangle">Rectangle</option>
<option value="circle">Circle</option>
</select>
<button id="addShapeBtn">Add Shape</button>
</div>
<!-- Custom Editor Menu (hidden by default) -->
<div id="editor">
<form id="editForm">
<div id="sizeFields"></div>
<label for="colorInput">Color:</label>
<input type="color" id="colorInput" value="#FF0000">
<br>
<button type="submit">Apply Changes</button>
<button type="button" id="deleteBtn" style="margin-left:10px;">Delete</button>
</form>
</div>
<script>
// Module aliases from Matter.js
const Engine = Matter.Engine,
Render = Matter.Render,
Runner = Matter.Runner,
Bodies = Matter.Bodies,
Composite = Matter.Composite,
Body = Matter.Body,
Mouse = Matter.Mouse,
MouseConstraint = Matter.MouseConstraint,
Query = Matter.Query;
// Create an engine with zero gravity and improved physics settings
const engine = Engine.create({
// Disable gravity completely
gravity: { x: 0, y: 0 },
// Enable continuous collision for better interactions
enableSleeping: false,
// Increase iterations for better collision resolution
positionIterations: 10,
velocityIterations: 8,
// Fix the slow leftward drift
constraintIterations: 10
});
const world = engine.world;
// Create a renderer and add it to document.body
const render = Render.create({
element: document.body,
engine: engine,
options: {
width: window.innerWidth,
height: window.innerHeight,
wireframes: false,
background: "#000000", // Black background
showSleeping: false,
// Add a slight blur for better appearance
showAngleIndicator: false
}
});
Render.run(render);
// Create runner
const runner = Runner.create();
Runner.run(runner, engine);
// Add walls to contain the shapes (top, left, right, bottom)
const wallOptions = {
isStatic: true,
restitution: 0.8, // Make walls bouncy
friction: 0.1, // Low friction
render: {
fillStyle: "#000066",
strokeStyle: "#00ffff",
lineWidth: 2
}
};
// Fixed floor that won't let shapes fall through
const ground = Bodies.rectangle(
window.innerWidth / 2,
window.innerHeight - 10,
window.innerWidth,
40,
wallOptions
);
// Add side walls and ceiling to keep shapes contained
const leftWall = Bodies.rectangle(0, window.innerHeight / 2, 40, window.innerHeight, wallOptions);
const rightWall = Bodies.rectangle(window.innerWidth, window.innerHeight / 2, 40, window.innerHeight, wallOptions);
const ceiling = Bodies.rectangle(window.innerWidth / 2, 0, window.innerWidth, 40, wallOptions);
// Add all walls to the world
Composite.add(world, [ground, leftWall, rightWall, ceiling]);
// Enable mouse drag from Matter.js
const mouse = Mouse.create(render.canvas);
const mouseConstraint = MouseConstraint.create(engine, {
mouse: mouse,
constraint: {
stiffness: 0.2,
render: { visible: false }
}
});
Composite.add(world, mouseConstraint);
render.mouse = mouse; // keep the mouse in sync with rendering
// Keep track of shapes that we add. (We will add a custom property "isShape" to exclude ground.)
// Also, store original dimensions for scaling.
function createShape(type) {
let body, custom = {};
// place at the center of the screen
const x = window.innerWidth / 2;
const y = window.innerHeight / 2;
// Common options for all shapes
const shapeOptions = {
restitution: 0.8, // Bouncier physics
friction: 0.1, // Lower friction
frictionAir: 0.01, // Slight air resistance to slow down floating shapes
render: {
fillStyle: "#FF0000",
strokeStyle: "#FFFFFF",
lineWidth: 2
},
// Improved collision filtering for stacking
collisionFilter: {
category: 0x0001, // Assign a category
mask: 0x0001 // Only collide with the same category
}
};
if (type === "rectangle") {
// default rectangle: width = 80, height = 50, color red.
const width = 80, height = 50;
body = Bodies.rectangle(x, y, width, height, shapeOptions);
custom.width = width;
custom.height = height;
} else if (type === "circle") {
const radius = 30;
body = Bodies.circle(x, y, radius, shapeOptions);
custom.radius = radius;
}
// Mark as our shape so we can skip ground etc.
body.isShape = true;
// Save the type and custom info
body.custom = custom;
body.shapeType = type;
// Add a small random velocity to make shapes float around
const angle = Math.random() * Math.PI * 2;
const speed = 0.5 + Math.random() * 1.5;
Body.setVelocity(body, {
x: Math.cos(angle) * speed,
y: Math.sin(angle) * speed
});
Composite.add(world, body);
}
// Handle Add Shape button
document.getElementById("addShapeBtn").addEventListener("click", function() {
const type = document.getElementById("shapeSelect").value;
createShape(type);
});
// --- Context Menu / Editing Panel Handling ---
let selectedBody = null; // The Matter body selected for editing
const editor = document.getElementById("editor");
const editForm = document.getElementById("editForm");
const sizeFieldsDiv = document.getElementById("sizeFields");
const colorInput = document.getElementById("colorInput");
const deleteBtn = document.getElementById("deleteBtn");
// Prevent the browser's default right-click on the renderer's canvas.
render.canvas.addEventListener("contextmenu", function(e) {
e.preventDefault();
});
// When right-clicking on the canvas, see if a shape was clicked.
render.canvas.addEventListener("mousedown", function(e) {
// Only consider right-click (button==2)
if (e.button !== 2) return;
// Get mouse position relative to canvas
const rect = render.canvas.getBoundingClientRect();
const mousePos = { x: e.clientX - rect.left, y: e.clientY - rect.top };
// Query all bodies at this point (filtering for ones that are our shapes)
const bodies = Composite.allBodies(world);
const hits = Query.point(bodies, mousePos).filter(b => b.isShape);
if (hits.length > 0) {
selectedBody = hits[0];
showEditor(e.clientX, e.clientY, selectedBody);
} else {
// If no shape found, hide editor.
hideEditor();
}
});
// Function to fill editor fields based on the selected shape
function showEditor(pageX, pageY, body) {
// Position the editor panel near the mouse
editor.style.left = pageX + "px";
editor.style.top = pageY + "px";
// Clear previous size fields.
sizeFieldsDiv.innerHTML = "";
// Depending on type, add appropriate input fields
if (body.shapeType === "rectangle") {
const widthLabel = document.createElement("label");
widthLabel.textContent = "Width:";
const widthInput = document.createElement("input");
widthInput.type = "number";
widthInput.id = "widthInput";
widthInput.value = body.custom.width;
widthInput.min = "10";
const heightLabel = document.createElement("label");
heightLabel.textContent = "Height:";
const heightInput = document.createElement("input");
heightInput.type = "number";
heightInput.id = "heightInput";
heightInput.value = body.custom.height;
heightInput.min = "10";
sizeFieldsDiv.appendChild(widthLabel);
sizeFieldsDiv.appendChild(widthInput);
sizeFieldsDiv.appendChild(heightLabel);
sizeFieldsDiv.appendChild(heightInput);
} else if (body.shapeType === "circle") {
const radiusLabel = document.createElement("label");
radiusLabel.textContent = "Radius:";
const radiusInput = document.createElement("input");
radiusInput.type = "number";
radiusInput.id = "radiusInput";
radiusInput.value = body.custom.radius;
radiusInput.min = "5";
sizeFieldsDiv.appendChild(radiusLabel);
sizeFieldsDiv.appendChild(radiusInput);
}
// Set the current color.
colorInput.value = body.render.fillStyle || "#FF0000";
// Show the editor div.
editor.style.display = "block";
}
// Hide the editor panel
function hideEditor() {
editor.style.display = "none";
selectedBody = null;
}
// Handle the form submission: update shape properties.
editForm.addEventListener("submit", function(e) {
e.preventDefault();
if (!selectedBody) return;
// Update size based on type.
if (selectedBody.shapeType === "rectangle") {
const newWidth = Number(document.getElementById("widthInput").value);
const newHeight = Number(document.getElementById("heightInput").value);
// Determine current dimensions from our custom data.
const curW = selectedBody.custom.width;
const curH = selectedBody.custom.height;
// Compute scale factors.
const scaleX = newWidth / curW;
const scaleY = newHeight / curH;
Body.scale(selectedBody, scaleX, scaleY);
// Update our stored dimensions.
selectedBody.custom.width = newWidth;
selectedBody.custom.height = newHeight;
} else if (selectedBody.shapeType === "circle") {
const newRadius = Number(document.getElementById("radiusInput").value);
const curR = selectedBody.custom.radius;
const scaleFactor = newRadius / curR;
Body.scale(selectedBody, scaleFactor, scaleFactor);
selectedBody.custom.radius = newRadius;
}
// Update color - both fill and stroke
selectedBody.render.fillStyle = colorInput.value;
selectedBody.render.strokeStyle = "#FFFFFF"; // White outline for neon effect
hideEditor();
});
// Handle deletion
deleteBtn.addEventListener("click", function() {
if (selectedBody) {
Composite.remove(world, selectedBody);
hideEditor();
}
});
// Hide the editor if clicking anywhere else
document.addEventListener("mousedown", function(e) {
// If the click isn't on the editor panel and isn't a right-click triggered on a shape, hide editor.
if (!editor.contains(e.target)) {
// For left-click only.
if (e.button === 0) hideEditor();
}
});
// Adjust canvas size on window resize.
window.addEventListener("resize", function() {
render.canvas.width = window.innerWidth;
render.canvas.height = window.innerHeight;
// Update all wall positions
Body.setPosition(ground, { x: window.innerWidth / 2, y: window.innerHeight - 10 });
Body.setPosition(leftWall, { x: 0, y: window.innerHeight / 2 });
Body.setPosition(rightWall, { x: window.innerWidth, y: window.innerHeight / 2 });
Body.setPosition(ceiling, { x: window.innerWidth / 2, y: 0 });
// Update ground dimensions
Body.setVertices(ground, [
{ x: 0, y: window.innerHeight },
{ x: window.innerWidth, y: window.innerHeight },
{ x: window.innerWidth, y: window.innerHeight - 40 },
{ x: 0, y: window.innerHeight - 40 }
]);
// Update ceiling dimensions
Body.setVertices(ceiling, [
{ x: 0, y: 0 },
{ x: window.innerWidth, y: 0 },
{ x: window.innerWidth, y: 40 },
{ x: 0, y: 40 }
]);
// Update side wall dimensions
Body.setVertices(leftWall, [
{ x: 0, y: 0 },
{ x: 40, y: 0 },
{ x: 40, y: window.innerHeight },
{ x: 0, y: window.innerHeight }
]);
Body.setVertices(rightWall, [
{ x: window.innerWidth - 40, y: 0 },
{ x: window.innerWidth, y: 0 },
{ x: window.innerWidth, y: window.innerHeight },
{ x: window.innerWidth - 40, y: window.innerHeight }
]);
});
// Add a small random velocity to all existing shapes when clicked
document.addEventListener("click", function(e) {
// Check if click was on a shape
const rect = render.canvas.getBoundingClientRect();
const mousePos = { x: e.clientX - rect.left, y: e.clientY - rect.top };
const bodies = Composite.allBodies(world);
const hits = Query.point(bodies, mousePos).filter(b => b.isShape);
if (hits.length > 0) {
const body = hits[0];
// Add a small random velocity
const angle = Math.random() * Math.PI * 2;
const speed = 0.5 + Math.random() * 1.5;
Body.setVelocity(body, {
x: Math.cos(angle) * speed,
y: Math.sin(angle) * speed
});
}
});
</script>
</body>
</html>
Key changes made:
Removed Gravity: Set gravity to { x: 0, y: 0 } in the engine creation options.
Added Floating Behavior:
Added a small random velocity to new shapes when they're created
Added a click handler that gives shapes a small random velocity when clicked
Added slight air friction (frictionAir: 0.01) to slowly reduce velocity over time
Improved Physics:
Increased restitution (bounciness) to 0.8 for better bouncing off walls
Kept low friction for smoother movement
Maintained collision filtering for better stacking
Positioning:
Changed the default spawn position to the center of the screen
Kept the walls to contain the shapes within the viewport
Now the shapes will float around the screen, bouncing off the walls and each other. You can click on shapes to give them a little push in a random direction. The shapes will slowly lose velocity due to the air friction, creating a nice floating effect.