Hi devs !
I finished my own top down camera for a rts game but I would like to know if the way I change the camera CFrame was the best !
I looks good it’s only if you see something that you would have done differently !
Here a video :
Here the code :
local RunService = game:GetService("RunService")
local UserInputService = game:GetService("UserInputService")
local TweenService = game:GetService("TweenService")
local TweenInformation = TweenInfo.new(0.5)
local Players = game:GetService("Players")
local Player = Players.LocalPlayer
local Mouse = Player:GetMouse()
local Camera = workspace.Camera
local Position = Vector3.new(0, 20, 0)
local LastPosition
local Inputs = {
[Enum.KeyCode.Right] = 0,
[Enum.KeyCode.Left] = 0,
[Enum.KeyCode.Down] = 0,
[Enum.KeyCode.Up] = 0,
}
local function ZoomIn()
if Position.Y > 20 then
Position -= Vector3.new(0, 5, 0)
end
end
local function ZoomOut()
if Position.Y < 100 then
Position += Vector3.new(0, 5, 0)
end
end
local function OnInputBegan(Input, GameProcessedEvent)
if Inputs[Input.KeyCode] then
Inputs[Input.KeyCode] = 1
end
end
local function OnInputEnded(Input, GameProcessedEvent)
if Inputs[Input.KeyCode] then
Inputs[Input.KeyCode] = 0
end
end
local function UpdatePosition()
local Velocity = Vector3.new(Inputs[Enum.KeyCode.Right] - Inputs[Enum.KeyCode.Left], 0, Inputs[Enum.KeyCode.Down] - Inputs[Enum.KeyCode.Up])
local Multiplicator = Velocity == Vector3.new(0, 0, 0) and 0 or 1 / math.sqrt(Velocity.X^2 + Velocity.Z^2)
Position += Velocity * Multiplicator
if Position ~= LastPosition then
LastPosition = Position
TweenService:Create(Camera, TweenInformation, {["CFrame"] = CFrame.new(Position) * CFrame.Angles(math.rad(-90), 0, 0)}):Play()
end
end
Camera.CameraType = Enum.CameraType.Scriptable
Camera.CFrame = CFrame.new(Position) * CFrame.Angles(math.rad(-90), 0, 0)
Mouse.WheelForward:Connect(ZoomIn)
Mouse.WheelBackward:Connect(ZoomOut)
UserInputService.InputBegan:Connect(OnInputBegan)
UserInputService.InputEnded:Connect(OnInputEnded)
RunService.RenderStepped:Connect(UpdatePosition)
Thanks you for the help and have a nice day !