It’s a simple scene with a camera (Orthographic Projection) and an object with sprite and colision components.
Just wanna make a click on the go and and get some info.
So , I have this error: WARNING:PHYSICS: Ray had 0 length when ray casting after applying physics scale, ignoring request.
I don’t get it. Tried suggestion from the stupid AI chat bot and nothing works.
I use Entity Picking | Defold example as reference. Camera in this example is not ortho. Is that an isue? Also there are 3d objects, not sprites - so is there a depth collision issue ?
Easiest way is to make this project available on github, maybe someone could give a look over it and explain to me what is going on!
Defold’s 2D physics is built on Box2D, and a ray in 2D has no depth to pass through. It’s a line segment in the XY plane, and as far as I know a ray that starts inside a shape doesn’t report that shape as hit. A click point is always inside the shape you want to detect, so a short ray at the cursor would almost never hit.
A single ray cast from far away to the click point doesn’t work either. It would hit anything on that line before the endpoint, including shapes that are entirely above the cursor. Casting from both sides and requiring the same object is how I got an exact “is this point inside the shape?” test.
One-ray solution: use 3D physics
With 3D physics, a ray travels along Z, passes through the box from front to back, and one ray is enough. This is the standard picking approach, and it works fine with sprites. It’s also what you’d use for a 3D model with a collision shape.
Beside previous explanation I’ve received, I got code from Claude.ai if I use 2D or 3D for Physics.
Physics Type: 2D (a workaround for 2D physics)
local function pick(x, y)
local groups = { CLICKABLE }
local down = physics.raycast(vmath.vector3(x, y + RAY_LEN, 0), vmath.vector3(x, y, 0), groups)
if not down then return nil end
local up = physics.raycast(vmath.vector3(x, y - RAY_LEN, 0), vmath.vector3(x, y, 0), groups)
if up and up.id == down.id then
return down.id
end
return nil
end
Physics Type: 3D
local function pick(x, y)
local hit = physics.raycast(vmath.vector3(x, y, 100), vmath.vector3(x, y, -100), { CLICKABLE })
return hit and hit.id
end