A simple cannon shooting a ball. How do I work with gravity?

  1. What do you want to achieve? A simple cannon that fires every 2 seconds and the cannonBall has an arch to it.

  2. What is the issue? The script works as intended, but the gravity is affected way too soon. So, it takes the initial look vector but then arches down immediately, I’ve messed around with the gravity vector and I can’t seem to make it go straight for a second at least and then arch down.

  3. What solutions have you tried so far? I have tried adding a task,wait to it, which works (almost) because at the start it actually archs upward which is odd, then it immediately is affected by gravity, similar to a roller coaster.

-- Variables
local cannon = script.Parent.FCannon
local bullet = game.ReplicatedStorage.Misc.cannonBall
local fireInterval = 2 -- Time between shots in seconds
local bulletSpeed = 100 -- Speed of the bullet
local gravity = Vector3.new(0, -900, 0) -- Gravity vector

-- Function to shoot the cannon
local function shootCannon()
	if bullet then
		-- Create a new bullet
		local newBullet = bullet:Clone()
		newBullet.CFrame = cannon.CFrame
		newBullet.Parent = workspace

		-- Create an attachment for the bullet
		local attachment = Instance.new("Attachment", newBullet)

		-- Apply initial velocity to the bullet
		local linearVelocity = Instance.new("LinearVelocity")
		linearVelocity.Attachment0 = attachment
		linearVelocity.VectorVelocity = cannon.CFrame.LookVector * bulletSpeed
		linearVelocity.RelativeTo = Enum.ActuatorRelativeTo.World
		linearVelocity.Parent = newBullet

		-- Apply continuous downward force to the bullet
		local vectorForce = Instance.new("VectorForce")
		vectorForce.Attachment0 = attachment
		vectorForce.Force = gravity
		vectorForce.RelativeTo = Enum.ActuatorRelativeTo.World
		vectorForce.Parent = newBullet

		-- Destroy the bullet after a certain time
		game.Debris:AddItem(newBullet, 5)
	end
end

-- Loop to continuously shoot the cannon
while true do
	shootCannon()
	wait(fireInterval)
end
1 Like

You’d need to be updating the linear velocity’s vector velocity every so often, as the look vector changes as the bullet arcs.

However, linear velocities let you get around this by using the relativeto property.

Set “relative to” to “attachment0”
Then set vectorVelocity to (0, 0, speed)

Depending on how your attachment is orientated, you may need to edit that (0,0,speed) vector. Such as: (0,0,-speed), or (speed,0,0)

Why are you creating another force for gravity if gravity is already applied to the bullet by default with roblox’s built in physics ? Also the reason i think the bullet goes straight down fast is because the gravity in your code is too strong the default value of gravity in roblox is Vector3.new(0,-192.2,0) approximatly and you need to multiply gravity with the bullet’s mass so that heavier or lighter objects get pushed with the same force so that one doesn’t go faster than others