🎯 Example Script - Raycast to Mouse Pointer

This script demonstrates how to fire a 2D Raycast from an object toward the mouse pointer, using correct screen-to-world coordinate conversion via ScreenToWorld().

💡 Important: In GameCrom, mouse coordinates are in screen space. To interact with world objects, you must always convert them using ScreenToWorld(). This script is ideal for aiming systems, turrets, guided weapons, selection, etc.

📜 Full Code

// ====================================================== 
// 🎯 Raycast_MouseTest.js — Camera-corrected coordinates
// ======================================================

function Start(obj) {
  obj.rayLength = 800;
  obj.hitInfo = null;
}

// ------------------------------------------------------
function Update(obj, dt) {
  if (!mouse) return;

  // 🟡 World origin (object center)
  const originX = obj.x + obj.w / 2;
  const originY = obj.y + obj.h / 2;

  // 🟢 Convert mouse coordinates to world space
  const { x: worldMouseX, y: worldMouseY } = ScreenToWorld(mouse.x, mouse.y);

  // 🚀 Cast the ray with debug visualization
  const hit = Raycast(
    originX,
    originY,
    worldMouseX,
    worldMouseY,
    obj.rayLength,
    true,   // debugDraw ON
    obj
  );

  obj.hitInfo = hit;

  // Log impact information
  if (hit && hit.object) {
    Log(`💥 Hit ${hit.object.name} at (${hit.x.toFixed(1)}, ${hit.y.toFixed(1)})`);
  }
}

📘 Quick Summary

🧠 Use cases:
⚙️ Optional extension: rotate object toward mouse
const angle = Math.atan2(worldMouseY - originY, worldMouseX - originX);
obj.rotation = angle * 180 / Math.PI;