Hello devs,
I am trying to create a spaceship which can fly toward a given target. I am using VectorForce and AlignOrientation (formerly BodyForce and BodyGyro) in order to move and direct the ship.
My main goal is to make it so that it can fly toward this part, no matter where it is in the workspace.
I also want to make the ships rotate by rolling toward the target, and then pitching toward it. This is very similar to the flight of a jet fighter. For now, I’m just turning the ship toward the goal part, letting the vectorforce do the rest. Gravity is off, since the setting is outer space.
my code after consulting roblox ai assistant:
local myModel = script.Parent
local flyforce = myModel.FlyForce
local flydir = myModel.FlyDirection
local target = workspace.Target
local targetpos = nil
local forceatt = myModel.Parts.Body.ForceAtt -- the attachment of the AlignOrientation
local forceattpos = forceatt.WorldPosition
targetpos = target.Position
-- Calculate the direction vector from the forceatt's position to the target position
local direction = (targetpos - forceatt.WorldPosition).Unit
print(direction)
-- Use the CFrame.lookAt function to create a CFrame that faces the direction
local newCFrame = CFrame.lookAt(forceatt.WorldPosition, forceatt.WorldPosition + direction)
print(newCFrame)
-- Get the rotation from the forceatt's current CFrame to the new CFrame
local rotation = forceatt.CFrame:toObjectSpace(newCFrame)
print(rotation)
-- Extract the angles from the rotation
local angleX, angleY, angleZ = rotation:toEulerAnglesXYZ()
print(angleX, angleY, angleZ)
-- Convert the angles from radians to degrees
local degreesX = math.deg(angleX)
local degreesY = math.deg(angleY)
local degreesZ = math.deg(angleZ)
print(degreesX, degreesY, degreesZ)
flydir.CFrame = CFrame.new(flydir.CFrame.Position) * CFrame.Angles(math.rad(degreesX), math.rad(degreesY), math.rad(degreesZ))
How would I go about doing this?
Thank you in advance.