How can I make an elastic collision in manim my code right now only move the bullet forward but not bounce back when the conditional statement is true what did I get wrong?
class Problem2(Scene):
def construct(self):
square = Square(side_length=3)
string = Line(square.get_corner(
UP), [0, 4, 0], buff=0)
bullet = Circle(radius=0.2, fill_color=GREY, fill_opacity=1)
bullet.shift(6*LEFT)
def updatebullet(bullet, dt):
bullet_vel = 2
bullet.shift(bullet_vel*dt)
if bullet.get_x() >= square.get_x():
bullet_vel = -bullet_vel
bullet.add_updater(updatebullet)
self.play(FadeIn(square, string))
self.play(FadeIn(bullet))
self.wait(10)
class Problem2(Scene):
def construct(self):
square = Square(side_length=3)
string = Line(square.get_corner(
UP), [0, 4, 0], buff=0)
bullet = Circle(radius=0.2, fill_color=GREY, fill_opacity=1)
bullet.shift(6*LEFT+DOWN)
self.flag = False
def updatebullet(bullet: Mobject, dt):
if bullet.get_x() >= square.get_x() or self.flag:
bullet_vel = -2
self.flag = True
else:
bullet_vel = 2
bullet.shift(np.array([bullet_vel, 0, 0])*dt)
bullet.add_updater(updatebullet)
self.play(FadeIn(square, string))
self.play(FadeIn(bullet))
self.wait(10)
Your problem was that every time the function was called, bullet_vel
was automatically assigned to 2
, then the shifting was done, and then it was changed. That meant the change never took effect, because each time the function was called it would reset.
All I have done in this code is moved the changing of the velocity before the movement of the bullet (I also added a flag so that it wouldn't get stuck alternating between positive and negative velocities)