// Create squares to grapple on
function createSquares() {
squares = []; // Clear existing squares
for (let i = 0; i < 10; i++) {
squares.push({
x: Math.random() * (canvas.width - 100) + 50,
y: Math.random() * (canvas.height / 2 - 100) + 50,
size: 30,
});
}
}
// Get the square under the mouse position
function getSquareUnderMouse(x, y) {
return squares.find(square =>
x >= square.x - square.size / 2 &&
x <= square.x + square.size / 2 &&
y >= square.y - square.size / 2 &&
y <= square.y + square.size / 2
);
}
Assistant
// Particle effect generator
function createParticles(x, y, color, options = {}) {
let { vxRange = [-1, 1], vyRange = [-3, -1], count = 10 } = options;
for (let i = 0; i < count; i++) {
particles.push({
x: x,
y: y,
vx: Math.random() * (vxRange[1] - vxRange[0]) + vxRange[0],
vy: Math.random() * (vyRange[1] - vyRange[0]) + vyRange[0],
alpha: 1,
color: color,
});
}
}
// Spawn enemies off-screen
function spawnEnemy() {
let side = Math.floor(Math.random() * 4);
let x, y;
if (side === 0) {
// Left
x = -20;
y = Math.random() * canvas.height;
} else if (side === 1) {
// Right
x = canvas.width + 20;
y = Math.random() * canvas.height;
} else if (side === 2) {
// Top
x = Math.random() * canvas.width;
y = -20;
} else {
// Bottom
x = Math.random() * canvas.width;
y = canvas.height + 20;
}
enemies.push({
x: x,
y: y,
size: 20,
speed: 2 + Math.random() * 1.5,
maxHealth: 30,
health: 30,
});
}
// Activate Ultimate
function activateUltimate() {
if (player.ultimateReady) {
player.ultimateActive = true;
player.ultimateReady = false;
player.ultimateTimer = player.ultimateDuration;
player.health = player.maxHealth;
player.stamina = player.maxStamina;
new Audio('./assets/ultimate.mp3').play();
// Add an effect for activation
createParticles(player.x, player.y, '255,215,0', { count: 50, vyRange: [-5, 0] }); // Gold color particles
}
}
// Update function
let lastTime = performance.now();
function update(deltaTime) {
// Player movements
// Left and right movement only
if (keys['a'] || keys['ArrowLeft']) {
player.vx -= player.speed;
}
if (keys['d'] || keys['ArrowRight']) {
player.vx += player.speed;
}
// Apply gravity
player.vy += gravity;
// Apply velocity
player.x += player.vx * 0.1;
player.y += player.vy * 0.1;
// Apply friction
player.vx *= friction;
player.vy *= friction;
// Update player stamina
if (player.grappling) {
if (!player.ultimateActive) {
player.stamina -= player.staminaDrain;
if (player.stamina <= 0) {
player.stamina = 0;
player.grappling = false;
player.grapplePoint = null;
}
}
} else {
if (!player.ultimateActive) {
player.stamina += player.staminaRegen;
if (player.stamina > player.maxStamina) {
player.stamina = player.maxStamina;
}
}
}
// Prevent player from falling through the lava
let lavaHeight = canvas.height - 50; // Lava height from the top
if (player.y + player.size / 2 > lavaHeight) {
player.y = lavaHeight - player.size / 2;
player.vy = 0;
if (!player.ultimateActive) {
// Damage player over time when in lava
player.health -= 0.5;
createParticles(player.x, player.y + player.size / 2, '255,69,0', { vxRange: [0, 0], vyRange: [-1, -0.5] });
}
}
// Grappling physics
if (player.grappling && player.grapplePoint) {
const dx = player.grapplePoint.x - player.x;
const dy = player.grapplePoint.y - player.y;
const dist = Math.sqrt(dx * dx + dy * dy);
const angle = Math.atan2(dy, dx);
const force = (dist - 100) * 0.02;
player.vx += Math.cos(angle) * force;
player.vy += Math.sin(angle) * force;
}
// Update enemies
enemies.forEach((enemy, eIndex) => {
const angle = Math.atan2(player.y - enemy.y, player.x - enemy.x);
enemy.x += Math.cos(angle) * enemy.speed;
enemy.y += Math.sin(angle) * enemy.speed;
// Check collision with player
const dx = enemy.x - player.x;
const dy = enemy.y - player.y;
const dist = Math.sqrt(dx * dx + dy * dy);
if (dist < enemy.size + player.size) {
if (!player.ultimateActive) {
// Damage player
player.health -= 1;
createParticles(player.x, player.y, '255,0,0'); // Red color
}
}
});
// Update projectiles
projectiles.forEach((proj, pIndex) => {
proj.x += proj.vx;
proj.y += proj.vy;
// Remove projectile if off-screen
if (proj.x < 0 || proj.x > canvas.width || proj.y < 0 || proj.y > canvas.height) {
projectiles.splice(pIndex, 1);
}
// Check collision with enemies
enemies.forEach((enemy, eIndex) => {
const dx = proj.x - enemy.x;
const dy = proj.y - enemy.y;
const dist = Math.sqrt(dx * dx + dy * dy);
if (dist < proj.size + enemy.size) {
// Enemy hit
enemy.health -= 10; // Damage to enemy
createParticles(enemy.x, enemy.y, '255,0,0'); // Red color
projectiles.splice(pIndex, 1);
// Check if enemy is dead
if (enemy.health <= 0) {
enemies.splice(eIndex, 1);
// Increase player's stamina by +20%
player.stamina += player.maxStamina * 0.2;
if (player.stamina > player.maxStamina) {
player.stamina = player.maxStamina;
}
// Increase score
score += 10; // Adjust the value as needed
// 30% chance to heal player by +30% health
if (Math.random() < 0.3) {
player.health += player.maxHealth * 0.3;
if (player.health > player.maxHealth) {
player.health = player.maxHealth;
}
createParticles(player.x, player.y, '0,255,0', { count: 20 }); // Green color for healing
}
new Audio('./assets/kill.mp3').play();
}
}
});
});
// Update particles
particles.forEach((part, index) => {
part.x += part.vx;
part.y += part.vy;
part.alpha -= 0.02;
if (part.alpha <= 0) {
particles.splice(index, 1);
}
});
// Spawn enemies at intervals
if (performance.now() - lastEnemySpawnTime > enemySpawnInterval) {
spawnEnemy();
lastEnemySpawnTime = performance.now();
}
// Prevent player from moving off-screen
if (player.x - player.size / 2 < 0) {
player.x = player.size / 2;
player.vx = 0;
} else if (player.x + player.size / 2 > canvas.width) {
player.x = canvas.width - player.size / 2;
player.vx = 0;
}
// Update Ultimate
if (player.ultimateActive) {
player.ultimateTimer -= deltaTime;
if (player.ultimateTimer <= 0) {
player.ultimateActive = false;
player.ultimateTimer = 0;
// Start cooldown (if you want to add one)
} else {
// Automatically shoot at the nearest enemy
if (enemies.length > 0) {
const nearestEnemy = enemies.reduce((closest, enemy) => {
const dx = enemy.x - player.x;
const dy = enemy.y - player.y;
const dist = Math.sqrt(dx * dx + dy * dy);
if (dist < closest.dist) {
return { enemy, dist };
} else {
return closest;
}
}, { enemy: null, dist: Infinity });
if (nearestEnemy.enemy) {
const angle = Math.atan2(nearestEnemy.enemy.y - player.y, nearestEnemy.enemy.x - player.x);
shootProjectile(null, null, angle);
}
}
// Ensure health and stamina are maxed out
player.health = player.maxHealth;
player.stamina = player.maxStamina;
}
}
// If you want to reset the ultimate after some cooldown, you can implement it here
}
// Draw function
let lavaWaveOffset = 0;
function draw() {
// Clear canvas with bloom effect
ctx.fillStyle = 'rgba(34,34,34,0.2)';
ctx.fillRect(0, 0, canvas.width, canvas.height);
To lock your game at 60 frames per second (FPS), you'll need to adjust your game loop to update at fixed intervals corresponding to 60 FPS. This ensures consistent game logic updates regardless of the actual rendering speed, providing smooth and predictable gameplay.
Here's how you can modify your existing code:
1. Define FPS Constants
At the top of your script, define constants for FPS and frame duration:
Modify your gameLoop function to accumulate the time passed and update the game state at fixed intervals:
let lastTime = performance.now();
let accumulator = 0;
function gameLoop() {
const now = performance.now();
let deltaTime = now - lastTime;
lastTime = now;
// Cap deltaTime to avoid spiral of death
if (deltaTime > 1000) deltaTime = FRAME_DURATION;
accumulator += deltaTime;
while (accumulator >= FRAME_DURATION) {
update(FRAME_DURATION);
accumulator -= FRAME_DURATION;
}
draw();
if (player.health > 0) {
requestAnimationFrame(gameLoop);
}
}
Explanation:
deltaTime Calculation: We calculate the time difference between the current frame and the last frame.
Accumulator: We accumulate deltaTime to keep track of the total elapsed time.
Fixed Time Step Update: Using a while loop, we call update() with a fixed FRAME_DURATION to ensure consistent updates at 60 FPS.
Capping deltaTime: By capping deltaTime, we prevent issues that occur if rendering slows down (known as the "spiral of death").
3. Modify the Update Function
Ensure your update(deltaTime) function uses the fixed deltaTime appropriately. Since deltaTime is now a fixed value (16.6667 ms), all time-based calculations should be adjusted accordingly.
For instance:
function update(deltaTime) {
// Convert deltaTime from milliseconds to seconds if needed
let deltaSeconds = deltaTime / 1000;
// Example: Move player
player.x += player.vx * deltaSeconds;
player.y += player.vy * deltaSeconds;
// Update ultimate timer
if (player.ultimateActive) {
player.ultimateTimer -= deltaTime;
// Other logic...
}
// Rest of your update logic...
}
4. Adjust Velocity and Movement Calculations
Since you're now using a fixed time step, you should adjust any movement or velocity updates to use deltaTime:
Note: Since deltaTime is always 16.6667, you might simplify the calculations. However, adjusting with deltaTime makes your code flexible if you decide to change FPS later.
5. Ensure Time-Based Mechanics Use deltaTime
Any time-based mechanics, such as cooldowns, timers, or animations, should use deltaTime:
After making these changes, test your game thoroughly to ensure everything runs smoothly at 60 FPS. Adjust any calculations as necessary to maintain consistent gameplay.
Final Note:
By implementing these changes, your game will run at a locked 60 FPS, providing a consistent experience across different devices and screen refresh rates.
Feel free to ask if you have any questions or need further assistance!