I have a script that rotates the character to where the mouse position is. The problem I ran into was that the script stops working after the character dies or respawns. I can’t seem to find a way to fix it.
Script
local Camera = workspace.CurrentCamera
local RunService = game:GetService("RunService")
local player = game.Players.LocalPlayer
local Mouse = player:GetMouse()
repeat wait() until player and player.Character and player.Character.PrimaryPart
local character = player.Character
local primary = character.PrimaryPart
local bodyGyro = Instance.new("BodyGyro")
bodyGyro.Parent = primary
bodyGyro.D = 40
bodyGyro.P = 10000
bodyGyro.MaxTorque = Vector3.new(4000000, 4000000, 4000000)
local function rayPlane(planepoint, planenormal, origin, direction)
return -((origin-planepoint):Dot(planenormal))/(direction:Dot(planenormal))
end
while true do
if character and primary then
local ray = Camera:ScreenPointToRay(Mouse.X, Mouse.Y)
local t = rayPlane(player.Character.Head.Position, Vector3.new(0, 1, 0), ray.Origin, ray.Direction)
local primaryPos = primary.Position
local plane_intersection_point = (ray.Direction * t) + ray.Origin
bodyGyro.CFrame = CFrame.new(primaryPos, Vector3.new(plane_intersection_point.X, primaryPos.Y, plane_intersection_point.Z))
RunService.Heartbeat:Wait()
end
end
You can add an update method for the character so that whenever the players character changes it will update the character variable…
Quick Example:
local PlayerService = game:GetService("Players")
local Player = PlayerService.LocalPlayer --Player Object
local Character = Player.Character -- Update variable
Player:GetPropertyChangedSignal("Character"):Connect(function()
Character = Player.Character
end)
Which Starter folder? If the script is in StarterPlayerScripts, it will run only once when the player joins the game. If it is in StarterCharacterScripts, it will run every time the player’s character respawns.