My CFrame declaration is far too lengthy. I feel like it could be shorter

Good morning,
I wrote a CFrame declaration that functions flawlessly, but in my perspective, it is far too long at 268 characters. Here’s the code:

newItem.Root.CFrame = CFrame.new(itemSlot.Position + Vector3.new(0, newItem.Root:GetAttribute("rootYPosition"), 0)) * CFrame.Angles(math.rad(newItem.Root.Orientation.X), math.rad(newItem.Root.Orientation.Y + math.random(0, 3)*90), math.rad(newItem.Root.Orientation.Z))

Though I am not very proficient with CFrames, I am very certain there is a feature that will allow this code to be smaller. Can someone help?

1 Like

I’m no expert, but you could use variables defined before it to reduce its length. Otherwise, to me it seems like it’s as short as it can be.

An example of variables that could be set here are the CFrame.Angles and the Vector3.new used.

The CFrame seems long because the values you are using are from a variable, not just an integer. You have to name the variable each time, so it will be long, but that is okay. As long as it works well.

1 Like

I know I can do that but I am more concerned with neat vertical code formatting, and that solution would cost me some extra lines, which would make it messy.

1 Like

Oh well then I wouldn’t know there. For me this seems pretty neat, but maybe there’s some standard for CFrames im not aware of.

1 Like

tried to shorten it
here’s my version of it:

local root = newItem.Root
local pos = itemSlot.Position + Vector3.new(0, root:GetAttribute("rootYPosition"), 0)
local ori = root.Orientation
local newY = ori.Y + math.random(0, 3) * 90
root.CFrame = CFrame.new(pos) * CFrame.Angles(math.rad(ori.X), math.rad(newY), math.rad(ori.Z))
1 Like

You could probably shorten the rotation part by writing:
newItem.Root.CFrame.Rotation * CFrame.Angles(0, math.random(0, 3)*math.pi/2, 0)

CFrame.Rotation just simply returns the rotation component of the CFrame, multiplying it the rotation above will rotate the original CFrame around the Y axis

1 Like

Thanks for sharing this solution, it’s exactly what I needed. But upon checking, I noticed that the orientation changes relative to the part instead of the world, which isn’t what I had in mind, the script doesn’t work as intended anymore. Any solutions for this problem?

Try swapping the order of operations around, like this:
CFrame.Angles(0, math.random(0, 3)*math.pi/2, 0) * newItem.Root.CFrame.Rotation

So now the orientation rotates around the world axis, before applying the part’s initial rotation.

1 Like

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