fix: Adjust player sprite rendering and collision box for proper scaling and alignment

This commit is contained in:
Kacper Kostka (aider) 2025-04-05 18:23:38 +02:00
parent 84e08b397d
commit f592c74412
2 changed files with 14 additions and 13 deletions

View File

@ -2,8 +2,8 @@
class Player extends Entity { class Player extends Entity {
constructor(x, y, options = {}) { constructor(x, y, options = {}) {
super(ENTITY_TYPES.PLAYER, x, y, { super(ENTITY_TYPES.PLAYER, x, y, {
width: 10, // Adjusted player size to better match 32x32 sprite width: 8, // Adjusted collision box size
height: 20, height: 16,
...options ...options
}); });
@ -124,9 +124,10 @@ class Player extends Entity {
ctx.save(); ctx.save();
ctx.translate(screenX, screenY); ctx.translate(screenX, screenY);
// Calculate sprite dimensions - make them proportional to collision box // Use fixed dimensions based on the actual sprite size
const spriteWidth = this.width * 1.6 * PIXEL_SIZE; // Wider sprite than collision box // Maintain the 32x32 aspect ratio
const spriteHeight = this.height * 1.6 * PIXEL_SIZE; // Taller sprite than collision box const spriteDisplayWidth = 32 * (PIXEL_SIZE / 2); // Scale based on pixel size
const spriteDisplayHeight = 32 * (PIXEL_SIZE / 2);
// Flip horizontally based on direction // Flip horizontally based on direction
if (this.direction < 0) { if (this.direction < 0) {
@ -139,8 +140,8 @@ class Player extends Entity {
this.sprite, this.sprite,
this.currentFrame * this.frameWidth, 0, this.currentFrame * this.frameWidth, 0,
this.frameWidth, this.frameHeight, this.frameWidth, this.frameHeight,
-spriteWidth / 2, -spriteHeight / 2 + 2, // +2 pixel offset to align feet with ground -spriteDisplayWidth / 2, -spriteDisplayHeight / 2 + 4, // Offset to align feet with ground
spriteWidth, spriteHeight spriteDisplayWidth, spriteDisplayHeight
); );
ctx.restore(); ctx.restore();
@ -160,10 +161,10 @@ class Player extends Entity {
ctx.strokeStyle = '#ff00ff'; ctx.strokeStyle = '#ff00ff';
ctx.lineWidth = 1; ctx.lineWidth = 1;
ctx.strokeRect( ctx.strokeRect(
screenX - spriteWidth / 2, screenX - spriteDisplayWidth / 2,
screenY - spriteHeight / 2 + 2, screenY - spriteDisplayHeight / 2 + 4,
spriteWidth, spriteDisplayWidth,
spriteHeight spriteDisplayHeight
); );
} }
} }

View File

@ -102,8 +102,8 @@ function spawnPlayer() {
PIXEL_SIZE = 6; PIXEL_SIZE = 6;
// Create player at specified coordinates // Create player at specified coordinates
// Adjust Y position to account for larger sprite size // Position adjusted for proper sprite alignment
player = createEntity(ENTITY_TYPES.PLAYER, 229, 55); player = createEntity(ENTITY_TYPES.PLAYER, 229, 50);
// Focus camera on player // Focus camera on player
worldOffsetX = player.x - (canvas.width / PIXEL_SIZE / 2); worldOffsetX = player.x - (canvas.width / PIXEL_SIZE / 2);