Help with Lock On Script

  1. What do you want to achieve?

I am trying to make a script, where you can move your cursor to another player or dummy and press L, and thus you “lock on” them.

  1. What is the issue?

Now, I have 2 issues. The first one is, I don’t know how to make CFrame.lookAt() or RenderStepped stop when L is press while a person is locked on. The second issue is that when the player presses W, they don’t move towards the dummy/player, they move wherever their camera is looking at, even though the player’s avatar is looking in the direction of the dummy/player.

  1. What solutions have you tried so far?

I tried to use Disconnect for RenderStepped loop to stop, but it’s not working. I was not able to find anything which could help me on Developer Hub or other places.

--Getting Services
local Players = game:GetService("Players")
local userInputService = game:GetService("UserInputService")
local RunService = game:GetService("RunService")

--Defining Variables
local locked_on = false
local humanoidGot = false
local Player = Players.LocalPlayer
local character = Player.Character or Player.CharacterAdded:Wait()
local player1 = character:WaitForChild("HumanoidRootPart")
print(player1)
local mouse = Players.LocalPlayer:GetMouse()
local hum
local RATE_PER_SECOND = 2
local render

--Finding the other player's Humanoid
userInputService.InputBegan:Connect(function(input, GPE)
	if GPE then return end
	if locked_on == false then
		if input.KeyCode == Enum.KeyCode.L then
			local mouseTarget = mouse.Target
			if mouseTarget.Parent:FindFirstChild("HumanoidRootPart") then
				hum = mouseTarget.Parent:WaitForChild("HumanoidRootPart")
				print("Retrieved HumanoidRootPart")
				print(hum)
				humanoidGot = true
			else
				print("Nope.")
			end
			if humanoidGot == true then
				print("Before stuff")
				locked_on = true
				RunService.RenderStepped:Connect(function(step)
					local increment = RATE_PER_SECOND * step
					player1.CFrame = CFrame.lookAt(player1.Position, hum.Position)
					wait(0.000001)
				end)
			else
				print("Wat.")
			end
		end
	end
	if locked_on == true then
		if input.KeyCode == Enum.KeyCode.L then
			--need to stop CFrame.lookAt() here
		end
	end
end)

I’ll appreciate it if someone can help me out here or give me a solution.

Instead you could try something like:

while locked_on == true do -- While locked on is true this will repeat.
    local increment = RATE_PER_SECOND * step
	player1.CFrame = CFrame.lookAt(player1.Position, hum.Position)
	wait(0.000001)
end

That was what I did first, but it looks really bad, that’s why I moved to RenderStepped.

So just do the same thing with Renderstepped or Heartbeat

RenderStepped doesn’t require a wait, you can disconnect the RenderStepped is by assigning the RenderStepped as a variable and then do :Disconnect

CFrame.lookAt(origin, thingtolookatposition)

One way is to force the player camera to look at the thing

1 Like

Oh Ok, I will try it. Thanks for suggesting!