1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
-- Trains must travel in a straight line with this!
addhook("ms100", "Train.MovePlayer")
local Train = {
	InitPos = { 0, 0 }, -- Initial coördinates (in pixels)
	EndPos = { 0, 0 }, -- Final coördinates (in pixels)
	Speed = 16, -- Pixels per second
	Direction = "N" -- N(orth), E(ast), S(outh) or W(est)
}
function Train:Init()
	-- Set the train at its initial location
	self.Image = image("gfx/sprites/train.bmp", -- Path to your train image
	 0, -- Do not rotate image
						0, -- Only draw if not covered by FoW
						1) -- Cover players
	imagepos(self.Image, unpack(self.InitPos), self:CalcRot())
	
	-- Calculate the time it takes to travel to the final destination
	self.Time = self:CalcTime()
end
function Train:CalcRot()
	-- Is rotation clockwise or counterclockwise?
	if self.Direction == "N" then return 0 end
	if self.Direction == "E" then return 90 end
	if self.Direction == "S" then return 180 end
	if self.Direction == "W" then return 270 end
end
function Train:CalcTime()
	-- Time in milliseconds or seconds?
	if self.Direction == "S" or self.Direction == "N" then local d = math.abs(InitPos[2] - EndPos[2])
	else local d = math.abs(InitPos[1] - EndPos[1]) end
	return (d / (self.Speed / 1000))
end
-- Call this function once and the train will ride all the way to EndPos
function Train:Move(id)
	-- id = the ID of the player in the train
	tween_move(self.Image, self.Time, unpack(self.EndPos))
	self.CurPos = { self.InitX, self.InitY }
	self.PlayerToMove = id
end
function Train.MovePlayer()
	if self.PlayerToMove ~= nil then
		-- Speed unpredictable with while? Will probably be the same as always, thus 50 times per second, thus every 2 frames.
		if Train.CurPos != Train.EndPos then
			if Train.Direction == "N" then
				-- Y becomes smaller?
				Train.CurPos[2] = Train.CurPos[2] - self.Speed / 100
				if Train.CurPos[2] < Train.EndPos[2] then Train.CurPos[2] = Train.EndPos[2] end
			elseif Train.Direction == "E" then
				-- X becomes greater
				Train.CurPos[1] = Train.CurPos[1] + self.Speed / 100
				if Train.CurPos[1] > Train.EndPos[1] then Train.CurPos[1] = Train.EndPos[1] end
			elseif Train.Direction == "S" then
				-- Y becomes greater?
				Train.CurPos[2] = Train.CurPos[2] + self.Speed / 100
				if Train.CurPos[2] > Train.EndPos[2] then Train.CurPos[2] = Train.EndPos[2] end
			elseif Train.Direction == "W" then
				-- X becomes smaller
				Train.CurPos[1] = Train.CurPos[1] - self.Speed / 100
				if Train.CurPos[1] < Train.EndPos[1] then Train.CurPos[1] = Train.EndPos[1] end
			end
			parse("setpos " .. Train.PlayerToMove .. " " .. Train.CurPos[1] .. " " .. Train.CurPos[2])
		else
			self.PlayerToMove = nil
		end
	end
end