Need help making ship turn towards part

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.

plane rotation axes

my workspace


(I want the ship to fly toward the highlighted block)

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.

Couldn’t you just do

local newCFrame = CFrame.lookAt(myModel.PrimaryPart.Position, targetpos) --Might return vector3 can't remember
	print(newCFrame)

myModel:PivotTo(newCFrame) 

This just makes it look at the part no matter what

even when I set the AlignOrientation to what you gave me, it makes the ship face one way and never redirect.

It worked, just had to realign the attachment. Thank you.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.