I have 2 tables that represent the X and Y axis of a graph, but how do I check the Y axis of “xPlayer”?
local xPlayer= math.random(xTable[1],xTable[#xTable])
local xTable = {0,2,4,4,6,9} --X axis of a graph
local yTable = {1,3,5,5,2,4} --Y axis of a graph
This may seem like a simple question, but I can’t find a way to do it no matter what.
I misread your post a bit, I rewrote it for you, this should work:
local xPlayer= math.random(1, xTable[#xTable])
local xTable = {0,2,4,4,6,9} --X axis of a graph
local yTable = {1,3,5,5,2,4} --Y axis of a graph
local yValue = yTable[xPlayer]
I’m not exactly sure what you’re trying to achieve though.
The green dots represent a numbers inside the xTable and yTable, for example xTable[5] and yTable[5] (6,2).
The black dotted line represents a random xPlayer value, 7 on this example.
I’m trying to find where the dotted black line intercepts with the green line.
local xTable = {0,2,4,4,6,9} --X axis of a graph
local yTable = {1,3,5,5,2,4} --Y axis of a graph
local xPlayer= math.random(xTable[1],xTable[#xTable])
-- First get nearest hardcoded points
local lowerX, higherX = xTable[1], xTable[#xTable]
local lowerIndex, higherIndex
-- What we're trying to do here is compare all values first with the given x to see if it's above or below the number
-- And then if it is indeed the closest number above/below
for index, x in pairs(xTable) do
if x < xPlayer and x > lowerX then
lowerX = x
lowerIndex = index
elseif x > xPlayer and x< higherX then
higherX = x
higherIndex = index
end
end
local lowerY, higherY = yTable[lowerIndex], yTable[higherIndex]
-- Get slope from points: Slope = (y2-y1)/(x2-x1)
local slope = (higherY - lowerY) / (higherX - lowerX)
-- Line formula is y = mx + b where m is the slope.
-- We need to find b and we already have two points on the line
-- Meaning we can put in its x and y values
-- b = y - mx
b = lowerY - slope * lowerX
-- b = higherY - slope * higherX would work as well
-- Now in y = mx + b, we have b and a random x, we just need to solve for y
yPlayer = slope * xPlayer + b
print(yPlayer) -- Done!
for index, x in pairs(xTable) do
if x < xPlayer and x > lowerX then
lowerX = x
lowerIndex = index
elseif x > xPlayer and x< higherX then
higherX = x
higherIndex = index
end
end
to this
for index, x in pairs(xTable) do
if x < xPlayer and x > lowerX then
lowerX = x
lowerIndex = index
else
higherX = x
higherIndex = index
end
end