How can I keep my bullets the same speed?

Hello, I’m making a gun with bullets and I kind of found a way to do it. I’m using tweens but now there’s a problem. If the bullets get shot already near the player it takes longer to get to its position but if you shoot further away it goes faster. I want to know how I can keep the tween/bullet speed precise every shot.
Video: https://gyazo.com/50f151777390cc7cd22897ea13cb37f4
Code:

		local bullet = Instance.new("Part", workspace)
		bullet.Size = Vector3.new(0.5, 0.5, 0.5)
		bullet.Position = script.Parent.Muzzle.Position
		bullet.Anchored = false
		bullet.CanCollide = false
		local tweenInfo = TweenInfo.new(.5, Enum.EasingStyle.Linear, Enum.EasingDirection.InOut)
		tweenService:Create(bullet, tweenInfo, {Position = mouse.Hit.p}):Play()
		game:GetService("Debris"):AddItem(bullet, 4)
2 Likes

The reason this happens is because you have tweeninfo time set to half a second. What happens then is the further it is, the greater the distance it has to travel so it speeds up to meet that half second requirement. The closer it is the less distance it needs to go so it will take its time.

To fix this you should maybe set time to a variable that adjusts based on the distance. If for example you want it to go 5 m/s, take the distance and divide it by the speed to get the time.

Examples:

If it has to go 10 meters, and I want it to go 5 m/s, set it to 2 seconds.

If it has to go 20 meters, and I want it to go 5 m/s, set it to 4 seconds.

4 Likes

This is what I thought, but I am having difficulty’s calculating this distance with magnitude. If you can give me a example code?..

1 Like

You could use a simple math formula to solve this.

To get the bullet distance you can get the magnitude between the hit position the raycast returns and the start position of the raycast.

local shotDistance = (hitPosition - startPosition).Magnitude

Then, you can use a simple equation.
In this example, you want the bullet to travel the same speed as it would if it were to travel an 100 stud distance in 0.5 seconds. Or you could just multiply it by the time you want it to take for the bullet to move one stud.

local bulletTime = shotDistance * 0.5 / 100 --To get the amount of time it takes to move in one stud
2 Likes

I believe you have to divide not multiply.

It seems perfectly fine to me from the video

1 Like

No, it’s because 0.5 / 100 is 0.005 seconds. That is just the time the bullet takes to move ONE stud, so you multiply it by the distance (which is also in studs).

Wouldn’t it be easier to just say, let the speed be 200 studs per second (or whatever you would want it to be set to) and divide distance by the speed?

You’d get the same result eitherway.

Your Method:

  • 0.5 / 100 = 0.005

  • 0.005 * 100 = 0.5

Other Method:
Given a rate of 200 sps (or any other desired speed).

  • 100 / 200 = 0.5
1 Like

This works! Thank you very much.