Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
2

How to make a part face towards the direction it is traveling?

Asked by 7 years ago

For example, if a part was moving downwards, upwards, or forwards, how can I make it so the rotation faces the direction it is traveling?

My attempt

while wait(1) do
    part.Rotation = part.Velocity
end

1 answer

Log in to vote
1
Answered by
Goulstem 8144 Badge of Merit Moderation Voter Administrator Community Moderator
7 years ago
Edited 7 years ago

This is kind of complex so bear with me and try to follow along. What you're trying to do can be accomplished with a BodyGyro object.

BodyGyros control the rotation of the object. If you give it a direction to look at, it will look at it. There's a CFrame constructor that helps out alot with this: CFrame.new(vector3 origin, vector3 lookat).

If you supply 2 vectors as arguments, it will take the first as the spot the CFrame is looking from. The second argument is used as the spot to look at.

So.. what you can do is use the Part's position as the 1st argument, the spot for the BodyGyro to look from. The second argument is where you need the part to be looking at, so it gets tricky.

You need to get a CFrame from the part's CFrame, relative to a location it would be in, if it kept going in the direction it is traveling. If you look at the literal definition of Velocity, it states it is 'the speed and movement direction of the object'. Keyword there my fellow developer: movement direction.

Multiply the part's current CFrame with a newly created CFrame. The new CFrame will consist of the part Velocity's X, Y, and Z components.

Here's the code, i'll comment so you can follow along.

local part = script.Parent --This is your part
--Place a BodyGyro in your part, this line references it.
local gyro = part:FindFirstChild("BodyGyro")

while wait() do --A constant loop
    gyro.CFrame = CFrame.new(part.CFrame.p, --This is the origin
            (CFrame.new(part.CFrame.p) --CFrame of Part's Position
            * CFrame.new( --Multiply by a new CFrame
                part.Velocity.X, --X velocity
                part.Velocity.Y, --Y velocity
                part.Velocity.Z --Z velocity
            ).p) --'.p' to convert the CFrame into a Vector
        )
end --'.p' is necessary because the constructor requires vectors as arguments
0
Awesome!!!! Thank!!! You!!! A+ my friend!!!! laughablehaha 494 — 7y
0
No problem :D Goulstem 8144 — 7y
Ad

Answer this question