Formula for random point within triangle

Hello,

Say that I have a right triangle:

  • A is 24 studs
  • B is 12 studs
  • And the Pythagorean theorem tells us that C is approximately 26.8 studs

One idea I had is to treat the hypotenuse as the slope of a line in a typical cartesian plane and use an integral to set a limit for the Y axis, but this seems like overkill given how simple of a problem this sounds.

I am looking for a formula or other method that can give me a random X and Y value on this triangle given A, B, and C, preferably without use of any trig or otherwise expensive math functions. Any ideas?

2 Likes

I threw this together and I honestly don’t think it’s very good because I didn’t look at any reference material for weighted averages but it runs. If you look for a solution elsewhere you would probably find better.

local P1 = Vector3.new(1,2,3)
local P2 = Vector3.new(2,4,6)
local P3 = Vector3.new(3,6,9)

local Weight = 1000

local W1 = math.random(0,Weight)
local W2 = math.random(0,Weight) 
local W3 = math.random(0,Weight)


local RandomPoint = (P1*W1 + P2*W2 + P3*W3)/(W1+W2+W3)
print(RandomPoint)

Forgot to mention that P1-P3 are the vertices of your triangle

1 Like

Will try it out thanks – not much material on this elsewhere, especially not on Roblox. Most tutorials are for Unity/UE4 and use built-in functions for meshes that aren’t available on Roblox.

Works great for our use case, thanks

I just realized an edge case where this would break, In the event W1, W2, and W3 are all 0 it will be vector3(0,0,0)/0 which is undefined so I don’t know how Roblox will handle it

1 Like

I’m using Random.new() rather than math.random() here so the chances that all 3 would be 0 is incredibly slim but I will clamp it anyways

Just thought of this, way simpler, maybe more performant, though it may have an unequal distribution in some cases.

local A = Vector3.new(1,2,3)
local B = Vector3.new(2,4,6)
local C = Vector3.new(3,6,9)

local Accuracy = 1000

local P1 = A:Lerp(B,math.random(0,Accuracy)/Accuracy)
local P2 = P1:Lerp(C,math.random(0,Accuracy)/Accuracy)
Print(P2)

Thanks, I will go with this option rather than the previous just for line preservation. The other one does have some evident distribution issues as well however this is not an issue since there will only be 1 point per wedge:
image

I don’t have an implementation for you but i did find this.
It says to convert your triangle into a parallelogram and then generate a random point on it. If the point is on the wrong half of the parallelogram mirror it to the other side (your triangle).
I think this would have a more even distribution.