Laser!

Hello everyone,
Is there an easy way of creating lasers? I think that one way could be have a really long laser sprite and spawn it, or use something like line renderer in unity. But how to create a similar thing in Defold?

Make an atlas, set edge extrusion to 2, place the sprite so that it’s left side is at 0,0 then stretch its go’s scale by x. You can calculate how far you stretch the laser based on the distance of how far you want the laser to go if the width of the laser sprite is 1, otherwise you divide by the sprite width. You can rotate the go by z to change the direction the laser is facing.

Here’s an example

LaserExample.zip (3.3 KB)

Here is the script in total

local function dist2d(x1, y1, x2, y2)
	return ((x2-x1)^2+(y2-y1)^2)^0.5
end

local function angle_of_vector_between_two_points(x1,y1, x2,y2) 
	return math.atan2(y2-y1, x2-x1) 
end

function init(self)
	msg.post(".", "acquire_input_focus")
	self.position = go.get_position()
	self.target_position = go.get_position()
	self.scale = go.get_scale()
end

function final(self)
	-- Add finalization code here
	-- Remove this function if not needed
end

function update(self, dt)
	local distance = dist2d(self.position.x, self.position.y, self.target_position.x, self.target_position.y)
	self.scale.x = distance
	go.set_scale(self.scale)
	local direction = angle_of_vector_between_two_points(self.position.x, self.position.y, self.target_position.x, self.target_position.y)
	local rotation = vmath.quat_rotation_z(direction)
	go.set_rotation(rotation)
end

function on_message(self, message_id, message, sender)
	-- Add message-handling code here
	-- Remove this function if not needed
end

function on_input(self, action_id, action)
	if action.x ~= nil then
		self.target_position.x = action.x
		self.target_position.y = action.y
	end
end

function on_reload(self)
	-- Add reload-handling code here
	-- Remove this function if not needed
end
11 Likes