Rotating a Part to Face the Mouse - Single Axis Only

Hey friends:

I’m trying to get a part to rotate to face the mouse, but maintain its orientation on two axis - in other words, it should spin like a hand on a clock, but not move forward or backward in and out of the clock face. Put another way, the part’s orientation should move on the X-axis only, and the Y and Z axis should stay at 0.

Adjusting the CFrame via the below works, but moves on all axis of course. I’ve struggled trying to maintain orientation with ‘fromOrientation’ and a bodygyro, but haven’t had luck.

local Shooter = game.Workspace.Shooter
local Players = game:GetService("Players")
local Player = Players.LocalPlayer
local Mouse = Player:GetMouse()

Mouse.Move:Connect(function()

Shooter.CFrame = CFrame.new(Shooter.Position, Mouse.Hit.Position)

end)

Appreciate any suggestions.

1 Like

I’ve done this before. All you have to do is this:

local pos = Vector3.new(Mouse.Hit.Position.X, part.Position.Y, Mouse.Hit.Position.Z)
part.CFrame = CFrame.new(part.Position, pos) 

This only depends on the axises your clock is rotating on.

You can change it to how you’d like.

Basically what is this doing is creating a Vector3.new() value, and setting it’s x and z values to the Mouse.Hit.Position's values, but the y is on the part.Position.Y.

For instance, if you wanted to be vertical, when the clock is rotating on the X axis, the code would look like this:

local pos = Vector3.new(part.Position.Y, Mouse.Hit.Position.Y, Mouse.Hit.Position.Z)
part.CFrame = CFrame.new(part.Position, pos) 

There are many types of parameters you can give CFrame.new(). The one I’m using is the second one. It looks like this:


local part.CFrame = CFrame.new(position, facing)

Where the first parameter is the position you want to be at, the second one is where you want to be looking. If we make the X value of the vector3 on the second parameter equal to the part’s current x axis, it’ll rotate parallel to it’s current x position.

1 Like

Success! Thank you so much Denver, that was it. It turned out that I needed to keep the x-axis defined by the part, then pass the y and z axis the position of the mouse, and the piece now moves around in a circle, but stays flat within a plane.

Working code and sample for reference:

local pos = Vector3.new(Shooter.Position.X, Mouse.Hit.Position.Y, Mouse.Hit.Position.Z)|
Shooter.CFrame = CFrame.new(Shooter.Position, pos)
2 Likes

I’m glad I could help. Like I said, I’ve dealt with the problem before. CFrames can be very complicated, but once you master it, it’s a breeze.

local pos = Vector3.new(part.Position.Y, Mouse.Hit.Position.Y, Mouse.Hit.Position.Z)

I believe you meant part.Position.X here.

1 Like

yes, I probably mistyped. Thank you.