Hi, I’m trying to make it so that when the player presses on the screen, a target sprite appears in the location then fades away. I also have a camera that follows the player, which has made this sorta difficult for me to do and I’m honestly lost. There are no errors and the world position of the sprite appears where I want it to, but it doesn’t appear on the screen. Here is the code:
local function complete(self)
local pos = vmath.vector3(-100, -100, 1) -- Move the target off-screen
go.set_position(pos, go.get_id())
end
function init(self)
msg.post(".", "acquire_input_focus")
end
function on_input(self, action_id, action)
if action_id == hash("touch") and action.pressed then
-- Ensure the target is visible
go.set("#target", "tint.w", 1)
-- Get the camera's view and projection matrices
local camera_url = msg.url("/cameraP2#camera") -
local view_matrix = go.get(camera_url, "view")
local projection_matrix = go.get(camera_url, "projection")
local screen_width = 1280
local screen_height = 640 -
-- Normalize screen coordinates to [-1, 1] range
local normalized_x = (2.0 * (action.x / screen_width)) - 1.0
local normalized_y = 1.0 - (2.0 * (action.y / screen_height)) -- Flip Y
-- Create a ray in normalized device coordinates (NDC)
local ray_ndc = vmath.vector4(normalized_x, normalized_y, -1, 1) -- Near plane
local ray_ndc_far = vmath.vector4(normalized_x, normalized_y, 1, 1) -- Far plane
-- Transform the ray to world space
local inv_view_proj = vmath.inv(projection_matrix * view_matrix)
local ray_world_near = inv_view_proj * ray_ndc
local ray_world_far = inv_view_proj * ray_ndc_far
-- Normalize the ray direction (convert to vmath.vector3)
local ray_dir = vmath.normalize(vmath.vector3(
ray_world_far.x - ray_world_near.x,
ray_world_far.y - ray_world_near.y,
ray_world_far.z - ray_world_near.z
))
-- Define a plane at Z = 400 (match the camera's Z position)
local plane_normal = vmath.vector3(0, 0, 1)
local plane_point = vmath.vector3(0, 0, 400)
-- Calculate the intersection of the ray with the plane
local denom = vmath.dot(plane_normal, ray_dir)
if math.abs(denom) > 0.0001 then -- Avoid division by zero
local t = vmath.dot(plane_point - vmath.vector3(ray_world_near.x, ray_world_near.y, ray_world_near.z), plane_normal) / denom
local world_pos = vmath.vector3(
ray_world_near.x + ray_dir.x * t,
ray_world_near.y + ray_dir.y * t,
ray_world_near.z + ray_dir.z * t
)
-- Debug: Print the world position
print("World position:", world_pos.x, world_pos.y, world_pos.z)
-- Move the target to the world position
go.set_position(world_pos, go.get_id())
else
print("Ray is parallel to the plane; no intersection.")
end
-- Animate the sprite's tint with a callback to the complete function
go.animate("#target", "tint.w", go.PLAYBACK_ONCE_FORWARD, 0, go.EASING_INOUTSINE, 0.5, 0, function() complete(self) end)
end
end```