Make part rotate around its edge

I am making a sort of turret that shoots at enemies. I would like the barrel of the turret to aim at the enemy, but I can’t figure out how to make it look right. (Ignore how bad the model of the turret is, it’s just a prototype)

This is what the turret looks like in the explorer.
image

Basically, there is a pole and a barrel which are next to eachother, like this.

I can make the barrel face the enemy with this code:

turret.Barrel.CFrame = CFrame.lookAt(turret.Barrel.Position, enemy.Position

But it ends up looking like this:


I would like the barrel to still be directly on top of the pole, not to the side of it. What code could I use to achieve this?

Thanks for the help!

1 Like

there is 2 options, use Welds/Motor6D and edit C0/C1
or just do this

turret.Barrel.CFrame = CFrame.new(turret.Pole.Position) -- setting it to pole position
turret.Barrel.CFrame = CFrame.lookAt(turret.Barrel.Position, enemy.Position) -- making barell look at enemy
turret.Barell.CFrame = turret.Barrel.CFrame * CFrame.new(0, 0, -turret.Barrel.Size.Z/2) -- moving barrel forward
turret.Barrel.CFrame = turret.Barrel.CFrame + Vector3.new(0, turret.Pole.Size.Y/2 + turret.Barrel.Size.Y, 0) -- moving barrel up

That code errored with “invalid argument #1 to ‘new’ (Vector3 expected, got CFrame)”

1 Like

I edited it, should have tested it before typing out :smile:

okay, thanks - trying that code now.

didn’t work, the turret looks like this:
image

Edit the Pivot Offset of the barrel so that the pivot point is where the pole is. Then, you can apply the same CFrame to both, which is a performance benefit as well.

should play with values like change the Z to Y (the longest size of your barrel) and so on, it should work

Oh, I forgot that its a thing! Yeah, you better should use that.

I tried that already, it didn’t do anything. Im pretty sure thats because CFrame.lookAt doesn’t work with PivotOffset (not very good with CFrames…)

You probably did that wrong
You should do

local pivot = Model:GetPivot()
local look = CFrame.new(pivot.Position, enemy.Position)
Model:PivotTo(look)

ok i will try this now. Thanks!

You forgot to use PivotTo, which can exclusively be used for pivot offsets. Another possible way to do this that might be better or worse is to group them together to apply the pivot to both in one line of code as opposed to two.

What would model be? The turret or the barrel

Barrel, because we are working with it

I tried this and it seemed to be facing the opposite direction of the enemy (maybe not exactly the opposite but it wasn’t facing towards the enemy) I can provide screenshots if you want

How could I use PivotTo with this?

You’d group the barrel and the pole together. Use PivotTo on the model. Simple as that. An advantage of this would be that you’re able to have the turret pivot point adjusted.

Is the CFrame inverted, or is it just the opposite?

But what would be the code to pivot it?

Model:PivotTo would be the code.