pong.gd 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. extends Node2D
  2. const PAD_SPEED = 150
  3. const INITIAL_BALL_SPEED = 80
  4. var ball_speed = INITIAL_BALL_SPEED
  5. var screen_size = Vector2(640, 400)
  6. # Default ball direction.
  7. var direction = Vector2.LEFT
  8. var pad_size = Vector2(8, 32)
  9. @onready var ball = $Ball
  10. @onready var left_paddle = $LeftPaddle
  11. @onready var right_paddle = $RightPaddle
  12. func _ready():
  13. screen_size = get_viewport_rect().size # Get actual size.
  14. pad_size = left_paddle.get_texture().get_size()
  15. func _process(delta):
  16. # Get ball position and pad rectangles.
  17. var ball_pos = ball.get_position()
  18. var left_rect = Rect2(left_paddle.get_position() - pad_size * 0.5, pad_size)
  19. var right_rect = Rect2(right_paddle.get_position() - pad_size * 0.5, pad_size)
  20. # Integrate new ball postion.
  21. ball_pos += direction * ball_speed * delta
  22. # Flip when touching roof or floor.
  23. if (ball_pos.y < 0 and direction.y < 0) or (ball_pos.y > screen_size.y and direction.y > 0):
  24. direction.y = -direction.y
  25. # Flip, change direction and increase speed when touching pads.
  26. if (left_rect.has_point(ball_pos) and direction.x < 0) or (right_rect.has_point(ball_pos) and direction.x > 0):
  27. direction.x = -direction.x
  28. ball_speed *= 1.1
  29. direction.y = randf() * 2.0 - 1
  30. direction = direction.normalized()
  31. # Check gameover.
  32. if ball_pos.x < 0 or ball_pos.x > screen_size.x:
  33. ball_pos = screen_size * 0.5
  34. ball_speed = INITIAL_BALL_SPEED
  35. direction = Vector2(-1, 0)
  36. ball.set_position(ball_pos)
  37. # Move left pad.
  38. var left_pos = left_paddle.get_position()
  39. if left_pos.y > 0 and Input.is_action_pressed(&"left_move_up"):
  40. left_pos.y += -PAD_SPEED * delta
  41. if left_pos.y < screen_size.y and Input.is_action_pressed(&"left_move_down"):
  42. left_pos.y += PAD_SPEED * delta
  43. left_paddle.set_position(left_pos)
  44. # Move right pad.
  45. var right_pos = right_paddle.get_position()
  46. if right_pos.y > 0 and Input.is_action_pressed(&"right_move_up"):
  47. right_pos.y += -PAD_SPEED * delta
  48. if right_pos.y < screen_size.y and Input.is_action_pressed(&"right_move_down"):
  49. right_pos.y += PAD_SPEED * delta
  50. right_paddle.set_position(right_pos)