3

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
Ducktor
  • 337
  • 1
  • 9
  • 27
  • how can you program vector stuff if you don't know the very basics of the related maths... you will always run into problems if you don't understand what you are doing. – Piglet Dec 25 '16 at 12:33
  • I agree with @piglet this stuff requires a knowledge of both the math, and the API. Things you clearly don't have a reasonable comprehension of. In my answer I combine both of these together, something that otherwise could not have been thought of. – warspyking Dec 25 '16 at 22:05

2 Answers2

10

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
MBo
  • 77,366
  • 5
  • 53
  • 86
1

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.

warspyking
  • 3,045
  • 4
  • 20
  • 37