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().
ScreenToWorld().
This script is ideal for aiming systems, turrets, guided weapons, selection, etc.
// ======================================================
// 🎯 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)})`);
}
}
ScreenToWorld() to avoid camera errors.const angle = Math.atan2(worldMouseY - originY, worldMouseX - originX);
obj.rotation = angle * 180 / Math.PI;