Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How do I make a cannonball always shoot in the direction of the muzzle?

Asked by 9 years ago

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)

1 answer

Log in to vote
0
Answered by 9 years ago

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.

0
Thanks for the help! I need to think like that more often. EasterCracker 5 — 9y
1
If this answered your question, please mark it as the answer! chess123mate 5873 — 9y
Ad

Answer this question