Lasers
Draw lines / lasers.
You can draw lasers / lines easily in Defold. You will need to place the laser/line segments in an atlas with edges extruded at 2.
Your segments need to have a width of 1. Then place their sprites on a .go so that their left side is at x of 0. This may require you to place them at x of 0.5 like in this example.
The important functions used in this example are dist2d to get the distances between two 2d points - this is used to determine how far to stretch the laser which is done through setting the x scale of the sprite's go, angle_of_vector_between_two_points which returns the radian angle between two 2d points, and vmath.quat_rotation_z which returns a quaternion of the rotation around the z axis based on the previously generated radian value.
laser.script
1
local function dist2d(x1, y1, x2, y2)
2
return ((x2-x1)^2+(y2-y1)^2)^0.5
3
end
4
5
local function angle_of_vector_between_two_points(x1,y1, x2,y2)
6
return math.atan2(y2-y1, x2-x1)
7
end
8
9
function init(self)
10
msg.post(".", "acquire_input_focus")
11
self.position = go.get_position()
12
self.target_position = go.get_position()
13
self.scale = go.get_scale()
14
go.animate(".", "scale.y", go.PLAYBACK_LOOP_PINGPONG, 1.5, go.EASING_INOUTSINE, 1.2 + math.random(30) * 0.01)
15
end
16
17
function update(self, dt)
18
local distance = dist2d(self.position.x, self.position.y, self.target_position.x, self.target_position.y)
19
self.scale.x = distance
20
go.set_scale(self.scale)
21
local direction = angle_of_vector_between_two_points(self.position.x, self.position.y, self.target_position.x, self.target_position.y)
22
local rotation = vmath.quat_rotation_z(direction)
23
go.set_rotation(rotation)
24
end
25
26
function on_input(self, action_id, action)
27
if action.x ~= nil then
28
self.target_position.x = action.x
29
self.target_position.y = action.y
30
end
31
end
32
Copied!
LaserExample.zip
4KB
Binary
Copy link