I have a third-person gun, as well as a script that aligns the player’s character to face the direction the mouse is pointing in. The issue is that as the mouse moves over objects, it tends to snap the character into that direction. This causes the gun to become inaccurate, with the beams firing in an odd direction. Is there any way to smoothen or minimize this?
Video here:
Code for character alignment here:
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)
idk if this will help but u can smooth using :lerp
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 = Root.CFrame:Lerp(CFrame.new(RootPos, Vector3.new(MousePos.X, RootPos.Y, MousePos.Z)), 0.1)
end)
Mouse.Hit.Position determines where the mouse is relative to objects in the world and not simply by where the players mouse is. You can try using UserInputService to get the raw mouse input instead, and use it to calculate which direction the character should be facing.
local UserInputService = game:GetService("UserInputService")
local Camera = game.Workspace.CurrentCamera
local function getMouseWorldPosition()
local mousePosition = UserInputService:GetMouseLocation() --Player's mouse on their screen
local ray = Camera:ViewportPointToRay(mousePosition.X, mousePosition.Y) --Converts the mouse position into a ray
--This determines how near or far you want the distance of the ray to go, which will influence how fast your character would rotate
local distance = 100 -- Change this as needed
local position = ray.Origin + ray.Direction * distance
return position
end
local mouseWorldPos = getMouseWorldPosition()
Maybe if the calculation determines that the player’s mouse is in the lower half of their screen you could try to use negative values to flip the character around. This is most likely a math issue involving the formula, so keep tweaking it until you get a result that suits you.