Created
March 28, 2020 11:42
-
-
Save vidarh/4af81af4aa9e7d2c9f8b6a8297a5e39d to your computer and use it in GitHub Desktop.
Simple demo of gravity in Dragonruby
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
# Click the Run game! button to execute the code. | |
def vector_add(v1,v2) | |
v1.zip(v2).map{|p1,p2| p1+p2} | |
end | |
# For demonstration purposes, we just blanket apply a terminal velocity. | |
# Set this low to see the effect. | |
def resistance(v, gravity) | |
# This only applies air resistance downwards, which is lazy | |
terminal_velocity = -100 | |
if v[1] < terminal_velocity | |
return [gravity[0],-gravity[1]] | |
end | |
# Set f higher the more air resistance an object produces. | |
# if f = 1, the object will float. | |
f = 0.1 | |
[-f*gravity[0],-f*gravity[1]] | |
end | |
def tick args | |
args.state.position ||= [400,100] | |
args.state.velocity ||= [10,20] | |
args.state.gravity ||= [0,-0.4] | |
# How much energy is lost in each direction on a bounce] | |
args.state.attenuation = [0.9,0.7] | |
args.lines << [0,100, 1280,100, 0, 255,0] | |
args.labels << [100,90, "Position: #{args.state.position.inspect}"] | |
args.labels << [100,70, "Velocity: #{args.state.velocity.inspect}"] | |
args.outputs.solids << [*args.state.position.to_a, 8,8, 255, 0,0] | |
# Update velocity based on gravity | |
r = resistance(args.state.velocity, args.state.gravity) | |
args.state.velocity= vector_add(args.state.velocity, args.state.gravity) | |
args.state.velocity= vector_add(args.state.velocity, r) | |
# Update position based on velocity | |
args.state.position= vector_add(args.state.position, args.state.velocity) | |
pos = args.state.position | |
# Colliding... | |
if pos[1] < 100 || | |
pos[1] > 720 || | |
pos[0] < 0 || | |
pos[0] > 1280 | |
args.state.velocity[0] = -args.state.velocity[0]*args.state.attenuation[0] | |
args.state.velocity[1] = -args.state.velocity[1]*args.state.attenuation[1] | |
end | |
# Make sure the object doesn't "escape" | |
pos[1] = 100 if pos[1] < 100 | |
pos[1] = 720 if pos[1] > 720 | |
pos[0] = 0 if pos[0] < 0 | |
pos[0] = 1280 if pos[0] > 1280 | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment