Math/Code problem. I have several objects on the screen, I want to take the position of all objects and average them, but...?
Ok, the problem goes like this. I need to get the average position of several objects on the screen. However, I also need to prioritize the objects closest to the right so that these objects have a higher influence of the end result of the calculation than those to the left. This solution needs to be smoothly scale-able so I can't just make more copies of the ones I want to prefer. Anyone got any ideas on how to do this.
husoski2019-04-12T09:20:26Z
Sounds to me like you're describing a weighted average.
average(x) = (Σ w[i]*x[i]) / (Σ w[i])
The x[i] values are the values to average, and w[i] is a *positive* weight value measuring the "importance" of the x[i] element. In your problem, as I read it, the w[i] will be computed from ("a function of") the x[i] value. The loop to compute that looks like:
sum_wx = sum_w = 0 for i = 0 to N-1: .... Compute w from x[i] .... sum_wx = sum_wx + w*x[i] .... sum_w = sum_w + w end for average = sum_wx / sum_w
To get a weight that varies the importance linearly from WLEFT to WRIGHT as x varies from XLEFT to XRIGHT, you can start by using the two-point formula to find an equation w = ax + b, given two (x,w) points (XLEFT, WLEFT) and (XRIGHT, WRIGHT).
m = (WRIGHT - WLEFT) / (XRIGHT - XLEFT) . . . . the slope of the line w = m * (x - XLEFT) + WLEFT
The values used to compute m are constant, so that computation can be done outside of all loops.
You can use any positive values for WLEFT and WRIGHT. Only the ratio WRIGHT/WLEFT matters. That measures the relative importance of an object on the far right compared to one on the far left. So, you can scale those constants to any convenient values so long as the ratio is what you wanted.