So I thought I had all the code right but I guess not. The target is found, the velocity is set, it just doesn’t move. I’m kinda stuck and don’t know how to fix.
local prepareEvent = game.ReplicatedStorage.MissilePrepare
local launchEvent = game.ReplicatedStorage.MissileLaunch
local fire = script.Parent.Effects.Fire
local smoke = script.Parent.Effects.Smoke
-- Variables
local missile = script.Parent -- Assuming you have a missile object in your workspace
local directedTarget = nil -- The target object you want the missile to track
local bodyVelocity = Instance.new("BodyVelocity")
bodyVelocity.Velocity = Vector3.new(0, 0, 0) -- Initialize with zero velocity
bodyVelocity.MaxForce = Vector3.new(math.huge, math.huge, math.huge) -- Set a high max force value to allow for rapid acceleration
bodyVelocity.Parent = missile
-- Function to find the nearest target
local function findNearestTarget()
local closestDistance = math.huge
local closestTarget = nil
-- Loop through all potential targets in the game
for _, potentialTarget in ipairs(game.Workspace:GetChildren()) do
-- Check if the potential target meets your criteria (e.g., is an enemy, has a specific tag, etc.)
if potentialTarget:GetAttribute("targetable") == true then
-- Calculate the distance between the missile and the potential target
local distance = (potentialTarget.Position - missile.Body.Top.Position).magnitude
-- Update the closest target if the potential target is closer
if distance < closestDistance then
closestDistance = distance
closestTarget = potentialTarget
end
end
end
return closestTarget
end
-- Function to update the missile's target
local function updateTarget()
directedTarget = findNearestTarget()
-- If a target is found, set the missile's target to that object
if directedTarget then
directedTarget = directedTarget
else
directedTarget = nil
end
end
-- Function to direct the missile towards the target
local function directMissile()
print(directedTarget)
-- Check if there is a valid target
if directedTarget then
local direction = (directedTarget.Position - missile.Body.Top.Position).unit
local speed = 100 -- Adjust the speed value as desired
bodyVelocity.Velocity = direction * speed
print(bodyVelocity.Velocity)
else
bodyVelocity.Velocity = Vector3.new(0, 0, 0) -- Stop the missile if there is no target
end
end
-- Call the updateTarget and directMissile functions periodically (e.g., in a loop)
prepareEvent.OnServerEvent:Connect(function(plr)
fire.Enabled = true
smoke.Enabled = true
end)
launchEvent.OnServerEvent:Connect(function(plr)
updateTarget()
directMissile()
print("Launched Missile")
end)