Setting the magnitude of a 2D Vector

11.6k views Asked by At

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
2

There are 2 answers

2
MBo On BEST ANSWER

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
0
warspyking On

The correct way to set the magnitude of a vector in roblox is to simply take the unit vector and multiply it by how long you wish for the vector to be:

function SetMagnitude(vec, mag)
    return vec.unit*mag
end

The unit vector is a vector identical in terms of direction, however with a magnitude of 1, which is why this will work :)

This is essentially a simplification of what the MBo's answer notes:

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

Since by multiplying a vector by a number you multiply it's all of it's components by the number:

new_v = v * New_Mag / Mag

And because v.unit has a magnitude of 1:

new_v = v.unit * New_Mag / 1

And any number divided by 1 is itself:

new_v = v.unit * New_Mag

So you can basically think of what I stated as the "correct way" as not just an alternative way, but a more efficient and cleaner solution.