Guest User

ball_script

a guest
Jul 26th, 2025
28
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. extends CharacterBody2D
  2.  
  3. enum {PADDLE_LAYER=(1<<0), BRICK_LAYER=(1<<2)}
  4.  
  5. const MIN_BOUNCE_ANGLE = deg_to_rad(20)
  6.  
  7. @export var SPEED := 250
  8.  
  9. var current_speed := SPEED
  10. var last_velocity = null
  11.  
  12. func _ready() -> void:
  13.     stop()
  14.  
  15.  
  16. func stop() -> void:
  17.     set_physics_process(false)
  18.  
  19.  
  20. func _physics_process(delta: float) -> void:
  21.     if velocity != last_velocity:
  22.         last_velocity = velocity
  23.     var collision = move_and_collide(velocity * delta)
  24.    
  25.     if collision:
  26.         __handle_collision(collision)
  27.  
  28.  
  29. func __handle_collision(collision: KinematicCollision2D):
  30.     var normal = collision.get_normal()
  31.     velocity = velocity.bounce(normal).normalized() * current_speed
  32.    
  33.     var collider = collision.get_collider()
  34.    
  35.     if collider.collision_layer & PADDLE_LAYER:
  36.         current_speed += 4
  37.         if collider.ball_hit_sidways() and velocity.y > 0:
  38.             velocity.y = -velocity.y
  39.     if collider.collision_layer & BRICK_LAYER:
  40.         collider.shater()
  41.  
  42.  
  43. func __bounce_with_minimum_angle(collision: KinematicCollision2D) -> Vector2:
  44.     var normal = collision.get_normal()
  45.     var bounced_velocity = velocity.bounce(normal).normalized()
  46.     var angle = abs(bounced_velocity.angle_to(normal))
  47.    
  48.     if angle < MIN_BOUNCE_ANGLE:
  49.         var sign = signf(bounced_velocity.cross(normal))
  50.         bounced_velocity = normal.rotated(sign * -MIN_BOUNCE_ANGLE).normalized()
  51.        
  52.     return bounced_velocity
  53.  
  54.  
  55. func start() -> void:
  56.     current_speed = SPEED
  57.     var angle_deg = randf_range(50, 120.0)
  58.     var angle_rad = deg_to_rad(angle_deg)
  59.     velocity = Vector2.RIGHT.rotated(angle_rad) * current_speed
  60.     set_physics_process(true)
  61.  
Advertisement
Add Comment
Please, Sign In to add comment