Recently, I've been learning how to script, and so I decided to make a simple cannon that fires whenever you press a trigger block. The problem is, I want the velocity of the cannonball that it launches to always be towards the direction of the muzzle. How do I go about doing this? Or is there a more efficient method?
gun = game.Workspace.Cannon trigger = game.Workspace.Trigger db = false function fire() if gun == nil then return end if db == false then db = true local projectile = Instance.new("Part") trigger.BrickColor = BrickColor.new(1004) projectile.Position = gun.Position projectile.BrickColor = BrickColor.new(1003) projectile.Shape = "Ball" projectile.Size = Vector3.new(3,3,3) projectile.Material = "Metal" projectile.Name = "Cannonball" projectile.CanCollide = false projectile.Velocity = ??? projectile.Parent = game.Workspace wait(5) trigger.BrickColor = BrickColor.new(1020) db = false end end script.Parent.Touched:connect(fire)
If there is a brick in the cannon that is facing the direction you want the cannonball to go, you can use its CFrame.lookVector. Multiply that by the magnitude of the velocity you want for the cannon ball and you're all set. ex, say there's a part named "Barrel" that points in the correct direction, you could say projectile.Velocity = gun.Barrel.CFrame.lookVector * 20
Say the closest thing to a 'Barrel' part is not facing the correct direction. You should experiment with CFrame.Angles(0, math.pi/2, 0) * gun.Barrel.CFrame.lookVector * 20
(also try -math.pi/2) to rotate the direction by 90 degrees.