Using BodyGyros to turn character not working?

I’m trying to get the character to face the nearest basketball hoop when dribbling, shooting and dunking. I try to achieve this using a function in each respective script called GetGoal(), and calling the selected goal within a script that rotates the player.

local function GetGoal()
    local function Finder()
		local goals = {}
		local hoopfolder = workspace.Hoops
        for i, v in pairs(hoopfolder:GetDescendants()) do
            if (v:IsA("MeshPart") and v.Name == "RimModel") then
                table.insert(goals, v)
            end    
        end
        return goals
    end

    local list = Finder()    
    local goal = nil
    local dist = 99999
    local temp = nil
    local human = nil
    local temp2 = nil
    local pos = Root.Position
    
    for i = 1, #list do
        temp2 = list[i]
        temp = temp2
        
        if (temp ~= nil) then
            local mag = (temp.Position - pos).magnitude
            
            if mag < dist then
                dist = mag
                goal = temp
            end
        end
    end
    
    return goal.Parent
end

local hoop = GetGoal()
local goal = hoop.RimModel

function rotateToHoop()
	local bg = Instance.new("BodyGyro", plr.Character.HumanoidRootPart)
			bg.MaxTorque = Vector3.new(math.huge, math.huge, math.huge)
			bg.P = 25000
			spawn(function()
				bg.CFrame = CFrame.new(plr.Character.HumanoidRootPart.Position, Vector3.new(goal.Position.X, plr.Character.HumanoidRootPart.Position.Y, goal.Position.Z)) 
				wait (.5)
				bg:Destroy()
			end)
end

For some reason, the player only looks at the hoop it picks the ball up nearest to, so it’s like the script only works once, yet the ball always shoots towards the nearest hoop using the exact same lines of code. To put this in perspective, I would be in front of one court shooting towards the rim for that respective court yet looking at the rim of a different court. The same issue also applies to dribbling which is meant to turn players towards the nearest rim.


(where i pick up ball)


(looking at initial rim while shooting towards nearest rim)


(Facing initial rim while dribbling next to nearest rim)

I’ve been unable to find solutions and am left at a complete brick wall leading me here today.

Thank you in advance!
-SpaceHex-

I fixed this, the problem was that I set the local variable outside of the function where I now needed them, so that every time I would call the function it would not refresh the goal finder and would stick to the same one!

Please note that CFrame.new(eye, lookAt) is deprecated. And CFrame.fromMatrix() should be used instead.

i don’t know why roblox deprecated it.

2 Likes