Help translating Python code to GDScript. Projectile trajectory.

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By DrSaito

I’m wondering if anyone could help translate this python code for projectile motion into GDScript.

I’m trying to translate this to 2D, but I keep getting an error that "Invalid operands ‘Vector2’ and _____ in operator ‘+’. I get the issue of adding non vectors to vectors isn’t allowed, but wondering how to get around that and get something functioning.

Basically I want to be able to set the theta angle, ball.m(mass) and the ball.p(momentum vector) and then calculate the ball position x and y.

Its from this video https://www.youtube.com/watch?v=F564RU3k528&

ground=box(pos=vector(0,-.2,0),size=vector(10,.4,2),color=color.green)
ball=sphere(pos=vector(-5,1.1,0),radius=.1, color=color.yellow, make_trail=True)
r0=ball.pos
g=vector(0,-9.8,0)
ball.m=0.2
v0=10
theta=70pi/180
ball.p=ball.m
v0*vector(cos(theta),sin(theta),0)

t=0
dt=0.001

while ball.pos.y>=0.1:
rate(1000)
Fnet=ball.mg
ball.p=ball.p+Fnet
dt
ball.pos=ball.pos+ball.p*dt/ball.m
t=t+dt

print(“dr final = “,ball.pos-r0,” m”)
print(“t final = “,t,” s”)

:bust_in_silhouette: Reply From: Lopy

Python is quite different from GDScript, and the code you found will be more difficult to translate than looking at a GDScript tutorial.

Here is a list of issues from those 10 lines to translate:

  • Your code is not part of a function, use func my_function(): to start a function declaration, and indent the code under it.
  • Named parameter filling (box(pos=vector…)) is not supported, as it apparently implies a heavy overhead.
  • “box”, “sphere”, “rate”, etc, are not defined. Use Godot primitives instead.
  • To create a Vector3, you write Vector3(0,1,2). Vector2(0,1) for a Vector2.
  • You assign values to undeclared variables. This is forbidden. Use “var” to introduce new variables: var r0 = ball.pos.
  • The constant pi is named PI in GDScript.

If you want to add a float to each field of a Vector2, you could write my_vector2 += Vector2(my_float, my_float).