Rotating a part using CFrame

I am trying to rotate a part when it is placed based on what orientation a user selects. The part rotates, however it isn’t rotating on what seems to be the right axis.

What I want:

What I get when using the script to rotate by 90 :

The code I am using with rotation equalling ‘90’:
p:SetPrimaryPartCFrame(p.PrimaryPart.CFrame * CFrame.Angles(0, math.rad(rotation), 0))

How could I rotate the model without it going off axis?

1 Like

Set the PrimaryPart of the model as the vertical post. Your model is rotating around the ‘bounding box’ axes, if you make the post the PrimaryPart it’ll CFrame around that item as the central part.

You want to rotate around the global y-axis rather than PrimaryPart.CFrame.UpVector which is what your current code does.

To do this:

p:SetPrimaryPartCFrame(CFrame.Angles(0, math.rad(rotation), 0) * (p.PrimaryPart.CFrame - p.PrimaryPart.CFrame.p) + p.PrimaryPart.CFrame.p)

Explanation:

First rotate by rotation radians around global y-axis then apply this to the primary part cframe as if it were centred at the global origin (0, 0, 0). Then add back the position of the primarypart so that it stays in place.