Created
December 6, 2019 17:05
-
-
Save 2DArray/73d537a886dbf6ff4630cbe2af40ab5d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- "bar" contains: | |
-- pt1 {x, y, vx, vy} or {x, y, oldx, oldy} | |
-- pt2 {x, y, vx, vy} or {x, y, oldx, oldy} | |
-- dist (intended distance between points) | |
function updatebar(bar) | |
-- find the current vector between our points | |
local dx = bar.pt1.x-bar.pt2.x | |
local dy = bar.pt1.y-bar.pt2.y | |
-- find the distance between the points | |
local dist = sqrt(dx*dx + dy*dy) | |
-- find the current error: how much extra distance do we have? | |
-- (we halve it because we're going to apply half-a-push to each point) | |
local extra = (dist - bar.dist)*.5 | |
-- maybe you only care about blocking "too far" positions, | |
-- while points are allowed to be closer together? | |
-- if (extra <= 0) return | |
-- normalize the direction-vector, then resize it | |
-- to match the size of our error | |
local pushx = (dx/dist) * extra | |
local pushy = (dy/dist) * extra | |
-- move both points together or apart (since "extra" might be negative) | |
bar.pt1.x-=pushx | |
bar.pt1.y-=pushy | |
bar.pt2.x+=pushx | |
bar.pt2.y+=pushy | |
-- if you're storing velocities (euler integration), | |
-- you'll need to modify those, too: | |
-- (this is a cheapo velocity-fixup method, but it's easy to tune) | |
local vstr = .5 -- tuning value | |
bar.pt1.vx -= pushx*vstr | |
bar.pt1.vy -= pushy*vstr | |
bar.pt2.vx += pushx*vstr | |
bar.pt2.vy += pushy*vstr | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment