Created
May 29, 2018 04:46
-
-
Save arachonteur/5606904bd3c7cf07c19bee37d65cab46 to your computer and use it in GitHub Desktop.
a lua camera
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- | |
-- | |
-- | |
-- | |
-- | |
local camera = { | |
TWEEN = 1, | |
SET = 2, | |
x = 0, | |
y = 0, | |
world = { | |
top = 0, | |
left = 0, | |
right = 640, | |
bottom = 360 | |
}, | |
start = { | |
x = 0, | |
y = 0 | |
}, | |
target = { | |
x = 0, | |
y = 0 | |
}, | |
speed = { | |
passive = 2, | |
active = 5, | |
}, | |
mode = 1, | |
tweenTime = 0, | |
offset = { | |
x = 0, | |
y = 0 | |
}, | |
shaking = false, | |
length = 0, | |
intensity = 0, | |
following = false, | |
} | |
function camera:shake(length, intensity) | |
self.shaking = true | |
self.intensity = intensity and intensity or 5 | |
self.length = length and length or 0.2 | |
end | |
function camera:update(dt, speed) | |
local horizontal, vertical = 0, 0 | |
local following = game:get(self.following) | |
if horizontal ~= 0 or vertical ~= 0 then | |
self.target.x = self.target.x - (horizontal * self.speed.active) | |
self.target.y = self.target.y - (vertical * self.speed.active) | |
elseif following then | |
self:setPosition(following.x, following.y) | |
end | |
if self.mode == self.TWEEN then | |
self.tweenTime = self.tweenTime + (dt * speed * self.speed.passive) | |
self.x = math.lerp(self.start.x, self.target.x, self.tweenTime) | |
self.y = math.lerp(self.start.y, self.target.y, self.tweenTime) | |
if self.tweenTime > 1 then | |
self.x = self.target.x | |
self.y = self.target.y | |
self.target.x = self.x | |
self.target.y = self.y | |
end | |
elseif self.mode == self.SET then | |
self.x = self.target.x | |
self.y = self.target.y | |
end | |
end | |
function camera:follow(entity) | |
self.following = entity | |
end | |
function camera:unfollow() | |
self.following = false | |
end | |
function camera:setPosition(x, y, mode, speed) | |
if speed then | |
self.speed = speed | |
end | |
if mode then | |
self.mode = mode | |
end | |
self.start.x = self.x | |
self.start.y = self.y | |
self.target.x = -x + math.floor(game.width / 2) | |
self.target.y = -y + math.floor(game.height / 2) | |
self.tweenTime = 0 | |
end | |
return camera |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment