How to get the x position of a object using js

I have looked thru the docs and I have tried a few different methods but they don’t work. anyone know how to get a objects x value using javascript?

Maybe (I didn’t try):

First solution:

// How to get x and y
function getSpriteXY(sprite) {
  if (!sprite) return { x: 0, y: 0 };
  
  return {
    x: sprite.getX?.() || 0,
    y: sprite.getY?.() || 0
  };
}
// Example
const coords = getSpriteXY(mySprite);
console.log(`Sprite posizione: x=${coords.x}, y=${coords.y}`);

Second solution (CHARA is the name of my sprite)

// Generic function to get sprite coordinates
function getSpriteCoordinates(sprite) {
  try {
    // Check if object exists and is valid
    if (!sprite) {
      console.warn('Invalid sprite');
      return null;
    }

    // Method 1: Top-left corner coordinates
    const x = sprite.getX?.() || 0;
    const y = sprite.getY?.() || 0;
    
    // Method 2: Center coordinates
    const centerX = sprite.getCenterXInScene?.() || (x + (sprite.getWidth?.() || 0) / 2);
    const centerY = sprite.getCenterYInScene?.() || (y + (sprite.getHeight?.() || 0) / 2);
    
    // Method 3: Dimensions
    const width = sprite.getWidth?.() || 0;
    const height = sprite.getHeight?.() || 0;
    
    // Method 4: Bottom-right corner coordinates
    const rightX = x + width;
    const bottomY = y + height;

    return {
      // Top-left corner coordinates
      x: x,
      y: y,
      
      // Center coordinates
      centerX: centerX,
      centerY: centerY,
      
      // Dimensions
      width: width,
      height: height,
      
      // Bottom-right corner coordinates
      rightX: rightX,
      bottomY: bottomY,
      
      // Complete bounds
      bounds: {
        left: x,
        top: y,
        right: rightX,
        bottom: bottomY,
        centerX: centerX,
        centerY: centerY
      }
    };
    
  } catch (error) {
    console.error('Error calculating sprite coordinates:', error);
    return null;
  }
}

// Usage example
function exampleUsage() {
  // Get all CHARA sprites
  const rs = this.runtimeScene;
  const charaObjects = rs.getObjects('CHARA') || [];
  
  charaObjects.forEach((chara, index) => {
    const coords = getSpriteCoordinates(chara);
    if (coords) {
      console.log(`CHARA ${index}:`, {
        name: chara.getAnimationName?.() || 'N/A',
        position: { x: coords.x, y: coords.y },
        center: { x: coords.centerX, y: coords.centerY },
        dimensions: { width: coords.width, height: coords.height }
      });
    }
  });
}

It’s getX() and getY()

See:
https://docs.gdevelop.io/GDJS%20Runtime%20Documentation/classes/gdjs.SpriteRuntimeObject.html

Make sure you’re pointing to an instance with a number in brackets.

const lastX = player[0].getX()

1 Like

thanks both of you!!! it works now!!!

2 Likes