How to code a smooth velocity brush?

For my project I’m trying to make a velocity brush that scales with how fast the mouse moves. The problem is the lines come out very jagged.

It takes the mouse’s speed, divides it by the brush size and multiplies that value with the brush size.


I’ve looked everywhere online and can’t find anything regarding this. Any help would be very much appreciated!

This is happening because you aren’t doing any substeps. Mouse movement is naturally jagged because frames don’t come in at specified times. Instead of processing mouse input directly, you should generate steps at specified time intervals and process those instead.

Your mouse might move 20px one frame and 50px the next. This causes the jagged edges you’re seeing. You can decide to use any fixed time step, like 0.01s. Look at the previous velocity, the previous position, the current velocity, and the current position. Then you can calculate the position and velocity of each substep.

function onCursor(position0, position1, time0, time1, velocity0)
   local deltaTime = time1 - time0
   local numSubsteps = deltaTime // SUBSTEP_TIME
   local velocity1 = (position1 - position0).Magnitude / deltaTime
  
   for n = 1, numSubsteps do
      local t = n*SUBSTEP_TIME
      local alpha = (t - time0) / deltaTime
      local projection0 = position0 + velocity0*alpha*deltaTime
      local projection1 = position1 - velocity1*(1-alpha)*deltaTime
      local position = projection0:Lerp(projection1, alpha)
      local velocity = velocity0:Lerp(velocity1, alpha)
      draw(position, velocity)
   
      if n == numSubsteps then
         return position, now+t, velocity
      end
   end

   return position0, time0, velocity0
end

This way your substeps will represent a smooth, consistent transition from one frame to the next. Just keep track of the final values from the previous step and use them as your 0 values in the next step. And use the mouse state you already have as a the 1 state.

Is velocity here a number or vector2?

The code you provided tries to add numbers to vector2 variables and throws an error. I don’t understand what its supposed to do.
image

What he’s trying to say is that when the game reads mouse inputs in happens on the frame not when you move the cursor, I have no clue what he even wrote. I believe what you should do is connect this function to UserinputService.InputChanged

local UserInputService = game:GetService("UserInputService")

UserInputService.InputChanged:Connect(function(_)
	if _.UserInputType == Enum.UserInputType.MouseMovement then
		--Run your function here
	end
end)

UserInputService.InputChanged runs every time an input changes regardless of frames, so it could run multiple times in a single frame.

– I think this would remove the jitteriness