Hello, I want to create a missile like targeting system. I have tried this using bodymovers and then updating the position with runservice.
This is what the code currently looks:
local missile = script.Parent -- The missile part
local target = workspace.Target -- The target part
local up_speed = 50 -- The speed at which the missile goes up
local fly_speed = 750 -- The speed at which the missile flies towards the target
-- Constants
local GRAVITY = 196.2 -- The gravity constant in Roblox (studs/s^2)
local TIME_STEP = 0.0167 -- The time step used in the RunService.Heartbeat event (seconds)
-- Create BodyMovers
local bv = Instance.new("BodyVelocity")
bv.MaxForce = Vector3.new(math.huge, math.huge, math.huge)
bv.Velocity = missile.CFrame:vectorToWorldSpace(Vector3.new(0, up_speed, 0))
bv.P = 5000
bv.Parent = missile
local bf = Instance.new("BodyForce")
bf.Force = Vector3.new(0, -missile:GetMass() * GRAVITY, 0)
bf.Parent = missile
game:GetService("RunService").Heartbeat:Connect(function()
if (missile.Position - target.Position).magnitude <= 10 then
bv:Destroy()
bf:Destroy()
return
end
-- Calculate the new velocity of the missile
local dir = (target.Position - missile.Position).unit
local vel = dir * fly_speed
-- Update the BodyMovers
bv.Velocity = Vector3.new(0, bv.Velocity.Y, 0)
bf.Force = Vector3.new(0, -missile:GetMass() * GRAVITY, 0) + missile.CFrame:vectorToWorldSpace(Vector3.new(0, 0, -vel.magnitude * missile:GetMass()))
wait(TIME_STEP)
end)
I want it to go up and then curve to the target while moving, like real missiles do.