# set the background image stage.set_background("jupiter") # create the rock with initial size and speed rock = codesters.Sprite("rock") rock.set_size(0.5) rock.set_x_speed(2) rock.set_y_speed(-3) # create the asteroid with initial size, position, and speed asteroid = codesters.Sprite("asteroid") asteroid.set_size(0.5) asteroid.go_to(-200, 0) asteroid.set_x_speed(-1) asteroid.set_y_speed(4) # create a function for the 's' key to make the rock smaller def s_key(): # make the rock smaller rock.set_size(0.8) # this line makes the code listen for the 's' key stage.event_key("s", s_key) # create a function for the 'w' key def w_key(): # make the rock bigger rock.set_size(1/0.8) # this line makes the code listen for the 'w' key to make the rock larger stage.event_key("w", w_key) # create a function for collision of the cars def collision(sprite, hit_sprite): # set variables size_sum = rock.get_size() + asteroid.get_size() x_vel_1 = sprite.get_x_speed() x_vel_2 = hit_sprite.get_x_speed() y_vel_1 = sprite.get_y_speed() y_vel_2 = hit_sprite.get_y_speed() rock_x = rock.get_x() rock_y = rock.get_y() asteroid_x = asteroid.get_x() asteroid_y = asteroid.get_y() # calculate the new velocities for 2-dimensional elastic collisions sprite.set_x_speed(x_vel_1 - ((2*asteroid.get_size())/size_sum) * ((x_vel_1 - x_vel_2)*(rock_x - asteroid_x) + (y_vel_1 - y_vel_2)*(rock_y - asteroid_y)) / ((rock_x - asteroid_x)*(rock_x - asteroid_x) + (rock_y - asteroid_y)*(rock_y - asteroid_y)) * (rock_x - asteroid_x)) sprite.set_y_speed(y_vel_1 - ((2*asteroid.get_size())/size_sum) * ((x_vel_1 - x_vel_2)*(rock_x - asteroid_x) + (y_vel_1 - y_vel_2)*(rock_y - asteroid_y)) / ((rock_x - asteroid_x)*(rock_x - asteroid_x) + (rock_y - asteroid_y)*(rock_y - asteroid_y)) * (rock_y - asteroid_y)) hit_sprite.set_x_speed(x_vel_2 - ((2*rock.get_size())/size_sum) * ((x_vel_2 - x_vel_1)*(asteroid_x - rock_x) + (y_vel_2 - y_vel_1)*(asteroid_y - rock_y)) / ((rock_x - asteroid_x)*(rock_x - asteroid_x) + (rock_y - asteroid_y)*(rock_y - asteroid_y)) * (asteroid_x - rock_x)) hit_sprite.set_y_speed(y_vel_2 - ((2*rock.get_size())/size_sum) * ((x_vel_2 - x_vel_1)*(asteroid_x - rock_x) + (y_vel_2 - y_vel_1)*(asteroid_y - rock_y)) / ((rock_x - asteroid_x)*(rock_x - asteroid_x) + (rock_y - asteroid_y)*(rock_y - asteroid_y)) * (asteroid_y - rock_y)) # this line makes the program detect collision and call the function above rock.event_collision(collision) # create a function to move the cars and bounce off walls def move(sprite): sprite.move_forward(1) if sprite.get_x() >= 250 or sprite.get_x() <= -250: sprite.set_x_speed(-sprite.get_x_speed()) if sprite.get_y() >= 250 or sprite.get_y() <= -250: sprite.set_y_speed(-sprite.get_y_speed()) # have the program run forever while True: move(rock) move(asteroid)
  • Run Code
  • Show Console
  • Codesters How To (opens in a new tab)