Search code examples
mathvectorluarobloxmagnitude

Setting the magnitude of a 2D Vector


trying to port something I made in javascript using the p5.js library which has a setMag function for 2D vectors

here's the documentation for it

How can I set the magnitude of a 2D vector in ROBLOX/lua?

function particle:update(mouseX,mouseY)
    local t=(Vector2.new(mouseX,mouseY)-(self.pos)).unit.setMag(self.acc)
    self.thrust=t
    self.vel = self.vel + self.thrust
    if self.vel.magnitude>self.maxspeed then
          self.vel.unit.setMag(self.maxspeed)
    end
    self.pos=self.pos+(self.vel)
    self.frame.Position=UDim2.new(0,self.pos.x,0,self.pos.y)
end

Solution

  • Let's vector components are vx, vy. It's current magnitude is

    Mag = Math.Sqrt(vx * vx + vy * vy)
    //as Piglet noticed in comment, you can use magnitude property
    

    To make vector with the same direction but change magnitude, just multiply components by ratio of magnitudes:

    new_vx = vx * New_Mag / Mag
    new_vy = vy * New_Mag / Mag