Hello! So, I’m trying to make an game with a RPG top-down camera view. I’m currently working on the aim aspect of the game where the character will face to the direction of where the mouse is.
I mean like this:
I was thinking of making the HumanoidRootPart face mouse.Hit but I don’t really know how to implement it. Help or tips are greatly appreciated.
I found this bits of script which actually work (kinda?).
local player = game.Players.LocalPlayer
local character = player.Character or player.CharacterAdded:Wait()
local rootPart = character:WaitForChild("HumanoidRootPart")
local mouse = player:GetMouse()
mouse.Move:Connect(function()
rootPart.CFrame = CFrame.new(rootPart.Position, rootPart.Position + mouse.Hit.p)
end)
However, it is extremely buggy and is almost unplayable. Is there any more efficient way of implementing such system?
local RunService = game:GetService("RunService")
local Players = game:GetService("Players")
local Player = Players.LocalPlayer
local Character = Player.Character or Player.CharacterAdded:Wait()
local HRP = Character:WaitForChild("HumanoidRootPart")
local Mouse = Player:GetMouse()
RunService.Heartbeat:Connect(function()
HRP.CFrame = CFrame.new(HRP.Position, HRP.Position + Vector3.new(Mouse.Hit.lookVector.x, HRP.CFrame.lookVector.y, Mouse.Hit.lookVector.z))
end)
this method should be more performance-friendly
Added some variables and an if statement to keep it from setting HRP Cframe when the player hasn’t moved
local RunService = game:GetService("RunService")
local Players = game:GetService("Players")
local Player = Players.LocalPlayer
local Character = Player.Character or Player.CharacterAdded:Wait()
local HRP = Character:WaitForChild("HumanoidRootPart")
local Mouse = Player:GetMouse()
local OldCFrame = nil
RunService.Heartbeat:Connect(function()
local NewCFrame = CFrame.new(HRP.Position, HRP.Position + Vector3.new(Mouse.Hit.lookVector.x, HRP.CFrame.lookVector.y, Mouse.Hit.lookVector.z))
if OldCFrame ~= NewCFrame then
HRP.CFrame = CFrame.new(HRP.Position, HRP.Position + Vector3.new(Mouse.Hit.lookVector.x, HRP.CFrame.lookVector.y, Mouse.Hit.lookVector.z))
OldCFrame = HRP.CFrame
end
end)
I’m assuming what you meant by ‘buggy’ is that the humanoid is trying to tilt to align with the mouse’s hit position while the humanoid is refusing at the same time due to built-in BodyGyro.
I’d make some slight changes to the code:
local Player = game.Players.LocalPlayer
local Character = Player.Character
local Root = Character.HumanoidRootPart
local Mouse = Player:GetMouse()
local RunService = game:GetService("RunService")
RunService.RenderStepped:Connect(function()
local RootPos, MousePos = Root.Position, Mouse.Hit.Position
Root.CFrame = CFrame.new(RootPos, Vector3.new(MousePos.X, RootPos.Y, MousePos.Z))
end)