-
Notifications
You must be signed in to change notification settings - Fork 0
/
pong.gd
87 lines (67 loc) · 2.51 KB
/
pong.gd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
extends Node2D
# class member variables go here, for example:
# var a = 2
# var b = "textvar"
# Member variables
var screen_size
var pad_size
var direction = Vector2(1.0, 0.0)
var left_score
var right_score
# Constant for pad speed (in pixels/second)
const INITIAL_BALL_SPEED = 80
# Speed of the ball (also in pixels/second)
var ball_speed = INITIAL_BALL_SPEED
# Constant for pads speed
const PAD_SPEED = 150
func _ready():
# Called every time the node is added to the scene.
# Initialization here
screen_size = get_viewport_rect().size
pad_size = get_node("left").get_texture().get_size()
left_score = 0
right_score = 0
set_process(true)
func _process(delta):
var ball_pos = get_node("ball").get_pos()
var left_rect = Rect2( get_node("left").get_pos() - pad_size*0.5, pad_size )
var right_rect = Rect2( get_node("right").get_pos() - pad_size*0.5, pad_size )
# Integrate new ball postion
ball_pos += direction * ball_speed * delta
# Flip when touching roof or floor
if ((ball_pos.y < 0 and direction.y < 0) or (ball_pos.y > screen_size.y and direction.y > 0)):
direction.y = -direction.y
# Flip, change direction and increase speed when touching pads
if ((left_rect.has_point(ball_pos) and direction.x < 0) or (right_rect.has_point(ball_pos) and direction.x > 0)):
direction.x = -direction.x
direction.y = randf()*2.0 - 1
direction = direction.normalized()
ball_speed *= 1.1
# Check gameover
if (ball_pos.x < 0 or ball_pos.x > screen_size.x):
if ball_pos.x < 0:
right_score += 1
set_label_text("right_score", "Right " + str(right_score))
else:
left_score += 1
set_label_text("left_score", "Left " + str(left_score))
ball_pos = screen_size*0.5
ball_speed = INITIAL_BALL_SPEED
direction = Vector2(-1, 0)
get_node("ball").set_pos(ball_pos)
# Move left pad
var left_pos = get_node("left").get_pos()
if (left_pos.y > 0 and Input.is_action_pressed("left_move_up")):
left_pos.y += -PAD_SPEED * delta
if (left_pos.y < screen_size.y and Input.is_action_pressed("left_move_down")):
left_pos.y += PAD_SPEED * delta
get_node("left").set_pos(left_pos)
# Move right pad
var right_pos = get_node("right").get_pos()
if (right_pos.y > 0 and Input.is_action_pressed("right_move_up")):
right_pos.y += -PAD_SPEED * delta
if (right_pos.y < screen_size.y and Input.is_action_pressed("right_move_down")):
right_pos.y += PAD_SPEED * delta
get_node("right").set_pos(right_pos)
func set_label_text(label_name, label_text):
get_node(label_name).set_text(label_text)