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

How to rotate a part based upon the camera angle?

Asked by 7 years ago

I've got a part I'm trying to select and move / rotate when it's clicked on. The moving the part, not so bad, I got that figured out. Now I'm looking to rotate the part, but not on its own local axis. I want to rotate it based on the camera's view. So for instance if you were looking at the part from above, and you used the WASD keys to rotate it, the W key would rotate it towards the top of the screen, S would be the bottom, A is the left, and D is the right. The same would be for if the camera is looking from any other angle. I think I at least have some Idea that it could be something to do with ObjectFrame and WorldFrame, but I am having issues figuring it out. Any assistance would be much appreciated!

Here's a code byte:

                    --rotate up
                    local rotation = object.CFrame*CFrame.fromEulerAnglesXYZ(math.rad(15),0,0)
                    movePartEvent:FireServer(object,mouse,d,rotation)

and since it's in a local script I have access to the mouse and the camera.

Mouse.Origin is a way I thought of going for referencing the camera's angle...

0
I have a problem similar to yours if you find how to plz tell me I will do the same on my side! Volt3Z 40 — 6y

1 answer

Log in to vote
0
Answered by
EgoMoose 802 Moderation Voter
6 years ago
Edited 6 years ago

I suppose there are a few ways you could do this, but the method I personally like is this

local function rotate(cf, relRot, cfAngles)
    local r = relRot - relRot.p;
    local cfAxis = CFrame.new(cf.p) * r;
    local offset = cfAxis:inverse() * cf;
    return (cfAxis * cfAngles) * offset;
end;

It works as follows.

  1. We find a CFrame that represents the position we want and the rotation that represents the axis we want to rotate by. So in your case, the relRot value would be camera.CFrame.

  2. We then find the offset needed to rotate from the CFrame in step 1 to get back to the original cf value. So in other words: cfAxis * offset = cf.

  3. We first rotate cfAxis thereby allowing us to use the axis of the relRot CFrame and then afterwards multiply by offset to get back to our original rotation.

Here's some example code:

local part = game.Workspace.Part;
local camera = game.Workspace.CurrentCamera;

part.CFrame = rotate(part.CFrame, camera.CFrame, CFrame.Angles(math.rad(10), 0, 0)); -- using the camera axis

part.CFrame = rotate(part.CFrame, CFrame.new(), CFrame.Angles(0, math.rad(10), 0)); -- using the world axis
Ad

Answer this question