sin/cos values not applying

31 views
Skip to first unread message

pole

unread,
Jan 12, 2024, 11:53:46 PMJan 12
to Glowscript Users
I tried to make a simple gravity simulation where you can use a switch to adjust the angle and launch the ball in that angle as well.
The sin and cos values from the switch(line 33, 34) show correctly, but they don't apply to the function for the launch button and seem to reset every time(line 38, 39).
Plus, I don't think this is the best way to code force that is applied for only a very short amount of time(like the launching force).
Any help? Code is below:

Web VPython 3.2
scene.autoscale = True
scene.center = vec(50,50,20)
crate = box(pos = vec(50, 50, 0), size = vec(100, 100, 10), color = color.cyan, opacity = 0.2)
ball = sphere(pos = vec(50, 100, 0), radius = 2, color = color.magenta)
ball.mass = 10
ball.vel = vec(0,0,0)
ball.force = vec(0,0,0)
ball.launchforce = vec(0,0,0)
gravity = -9.8 * 1
theta = 0
sinev = 0
cosv = 0
#^^____________ constants
button( bind=B, text='launch' )
slider( bind=S, text='control launch angle' )
#^^____________ controls
boundary_xmin = crate.pos.x - crate.size.x/2 + 2
boundary_xmax = crate.pos.x + crate.size.x/2 - 2
boundary_ymin = crate.pos.y - crate.size.y/2 + 2
boundary_ymax = crate.pos.y + crate.size.y/2 - 2
def boundary(obj, y_min, y_max, x_min, x_max):
    if obj.pos.y < y_min:
        obj.pos.y = y_min
    if obj.pos.y > y_max:
        obj.pos.y = y_max
    if obj.pos.x < x_min:
        obj.pos.x = x_min
    if obj.pos.x > x_max:
        obj.pos.x = x_max
def S(s):
    theta = radians(s.value*180)
    print(sin(theta))
    print(cos(theta))
def B(b):
    ball.launchforce.y = 75000 * sin(theta)
    ball.launchforce.x = 75000 * cos(theta)
    print(sin(theta))
    print(cos(theta))
t = 0
dt = 0.01

while t<100000:
    rate(100)
   
    ball.force.x = ball.launchforce.x
    ball.launchforce.x = 0
    ball.force.y = ball.launchforce.y + ball.mass * gravity
    ball.launchforce.y = 0
   
    ball.vel.x += ball.force.x/ball.mass * dt
    ball.vel.y += ball.force.y/ball.mass * dt
   
    boundary(ball, boundary_ymin, boundary_ymax, boundary_xmin, boundary_xmax)
   
    ball.pos += ball.vel * dt
   
    t += dt

Max DeMarr

unread,
May 30, 2024, 8:11:31 PMMay 30
to Glowscript Users
Hello,

Apologies for the old reply. Likely, you have already found the solution needed for this. For any future readers, the theta variable being written to in the sliders definition isn't the global theta but a new local one. The following fixes this issue:
def S(s):
    global theta

    theta = radians(s.value*180)
    print(sin(theta))
    print(cos(theta))

Note to the author: You should put line 56 before line 54 as ball.vel will be non-zero when spamming the launch button which can force the ball outside of the boundaries.

Best,
- Maximillian
Reply all
Reply to author
Forward
0 new messages