I’m currently working on a tower attack system for my tower defense game, and I recently came across an issue relating to how the tower is facing the enemy. My issue at the moment is if an enemy is higher than the tower or is below it, instead of facing straight and attacking that way, it instead faces towards the enemy which causes it to somewhat float:
This is the code that is facing the tower towards the enemy:
local targetCFrame = CFrame.lookAt(Tower.HumanoidRootPart.Position, target.HumanoidRootPart.Position);
Tower.HumanoidRootPart.CFrame = targetCFrame;
How would I prevent the tower from looking up or down? Any sort of help is appreciated.
local towerPos = Tower.HumanoidRootPart.Position
local targetPos = target.HumanoidRootPart.Position
local lookDir = ((targetPos - towerPos) * Vector3.new(1, 0, 1)).Unit
local targetCFrame = CFrame.lookAt(towerPos, towerPos + lookDir)
Tower.HumanoidRootPart.CFrame = targetCFrame
The * operator for 2 Vector3s multiplies them together component-wise, so the result is (x, y, z) = (x1 * x2, y1 * y2, z1 * z2). Multiplying by 0 sets to 0, multiplying by 1 does nothing. So multiplying a Vector by (1, 0, 1) results in (x, y, z) = (x1, 0, z1), causing the direction vector to no longer take into account the vertical displacement between tower and target.