I'm developing a Javascript animation using matter.js. Here is the link:
https://codepen.io/Sergio-Escalona/pen/VwNrwbw
document.addEventListener("DOMContentLoaded", function () {
// Basic setup
let Engine = Matter.Engine,
World = Matter.World,
Bodies = Matter.Bodies,
Body = Matter.Body;
let engine = Engine.create();
engine.world.gravity.y = 0; // No gravity for a space-like effect
let render = Matter.Render.create({
element: document.body,
engine: engine,
options: {
width: window.innerWidth,
height: window.innerHeight,
background: 'transparent',
wireframes: false // for sprite rendering
}
});
// Create static walls
let thickness = 50; // Ensures ducks don't escape through fast movements
let wallOptions = { isStatic: true, restitution: 1.0 }; // Perfectly elastic collisions
let ground = Bodies.rectangle(window.innerWidth / 2, window.innerHeight + thickness / 2, window.innerWidth, thickness, wallOptions);
let leftWall = Bodies.rectangle(-thickness / 2, window.innerHeight / 2, thickness, window.innerHeight, wallOptions);
let rightWall = Bodies.rectangle(window.innerWidth + thickness / 2, window.innerHeight / 2, thickness, window.innerHeight, wallOptions);
let topWall = Bodies.rectangle(window.innerWidth / 2, -thickness / 2, window.innerWidth, thickness, wallOptions);
World.add(engine.world, [ground, leftWall, rightWall, topWall]);
// Function to add a new duck with random selection for black duck
function addDuck() {
let safeMargin = 100; // A margin to avoid spawning too close to the edge
let radius = 25;
// Randomly choose the texture for the duck
let textureUrl = Math.random() < 0.9 ?
'https://assets.codepen.io/12210161/duckling-svgrepo-com.svg' :
'https://assets.codepen.io/12210161/duckling-svgrepo-com-bk.svg';
let duck = Bodies.circle(Math.random() * (window.innerWidth - 2 * safeMargin) + safeMargin, Math.random() * (window.innerHeight - 2 * safeMargin) + safeMargin, radius, {
restitution: 0.9,
friction: 0.0,
frictionAir: 0.0,
density: 0.001,
render: {
sprite: {
texture: textureUrl,
xScale: 0.1,
yScale: 0.1
}
}
});
// Apply an initial force to ensure movement
Body.applyForce(duck, {x: duck.position.x, y: duck.position.y}, {x: (Math.random() - 0.5) * 0.05, y: (Math.random() - 0.5) * 0.05});
World.add(engine.world, duck);
}
document.getElementById("oneMoreBtn").addEventListener("click", addDuck);
// Start the engine and renderer
Engine.run(engine);
Matter.Render.run(render);
// Initially add a duck to start with
addDuck();
});
I don't know why black ducks are smaller than the regular ones. The svg files dimensions (px) are exactly the same and I can't find where is the problem.
Can anyone help me to solve it?
Thanks in advance!!!
I've checked the svg files and both are exactly the same size. About the Javascript code I can't find anything beyond the render scale but I think it shouldn't be the problem.