The cost of creating a single ray cast request/response is much higher than the cost of an actual physics geometric query.
This is because raycasting in Defold made by sending and receiving messages. Messaging by itself are very costly system. It doubles with raycasts – one raycast results in two messages.
Look at this:
local post = msg.post
local ray_cast = physics.ray_cast
local random = math.random
local sin = math.sin
local cos = math.cos
local pi = math.pi
local from = vmath.vector3(100, 568, 0)
local to = vmath.vector3(300, 568, 0)
local groups = { hash("test") }
math.randomseed(os.time())
function update(self, dt)
for _ = 1, 400 do
--post("#", "test")
ray_cast(from, to, groups)
-- do
-- local x = random()
-- local y = random()
-- local z = random()
-- self.d = x + y + z
-- self.a = sin(random() * pi)
-- self.b = cos(random() * pi)
-- self.c = (self.a + self.b) * dt
-- end
end
end
function on_message(self, message_id, message)
end
The solution is to make raycasts a direct function call. Without messages, without callbacks, only a synchronous, blocking function that returns the result of a raycast response.
BTW, the code inside do…end block is performance equivalent of msg.post() function. Think about it when you want to post message next time.