How to modify velocity without overwriting it?

Hi! Sorry if the title is confusing: pretty much, I’m making a movement game and I needed to create a controller for the character. So, I did that, but an issue with it was when I needed to overwrite the velocity multiple times at the same time. So I created a script that combined and delete velocities into one velocity:


local module = {}
module.__index = module

local objects = {}

local RUN_SERVICE = game:GetService("RunService")
--local GRAVITY = 140

function module.get (object:Instance)
	if objects[object] then
		return objects[object]
	else
		local self = setmetatable({}, module)
		
		if object:IsA('Model') then
			self.object = object.PrimaryPart
		else
			self.object = object 
		end

		if not self.object then error("Object doesn't exist!") end
		
		objects[object] = self

		self.velocities = {}

		self.runServiceConnection = RUN_SERVICE.PreSimulation:Connect(function()
			if next(self.velocities) then 
				local vel = Vector3.new()
				for index, velocity in self.velocities do
					if velocity then
						vel += velocity
					end
				end
				self.object.AssemblyLinearVelocity = vel
			end
		end)

		return self
	end
end

-- Sets a velocity to a value, and returns the value
function module:SetVelocity(key, value: Vector3)
	self.velocities[key] = value
	return value
end

function module:GetVelocity(key)
	return self.velocities[key]
end

function module:ClearVelocity()
	self.velocities = {}
end

return module.get

But there are multiple issues with this:

  1. Can’t apply impulses
  2. Can’t do stuff like modifying the velocity each time to keep it midair (Fixable tho)

I feel like there is a constraint to do this rather than what I’m doing, so I just want to make sure I’m not wasting my time. Thanks!

The velocity is being overwritten because you are setting AssemblyLinearVelocity instead of incrementing a force.

self.object.AssemblyLinearVelocity = vel

Ok, but if I increment it, it will add on indefinitely and go much faster and farther than how much I want it to go. Am I missing something here??? It’s not just impulses btw some of the velocities are a constant force.

Create a default speed and add impulses on top of the default speed. This speed can be a real default speed, or a speed that comes from factors such as equipment, etc. and then if you need to propel the object, you use the default speed and add the impulse. (Stop getting the speed and manipulate a new one, the same way you are doing, but adding your impulses on top of it)

Example: Default speed (50) + Impulse (10).

If a constant speed is required, reduce the speed until it reaches the default speed after an impulse is applied. You could manage how much force an object loses each frame [task.wait()], by creating your own gravity/force system.

1 Like

Thanks, but is there really not a constraint that does this ?