Skip to content

Commit bcc8f64

Browse files
committed
Platformer 2D: Simplify controller with proper is_on_floor usage
1 parent 3541aab commit bcc8f64

File tree

1 file changed

+13
-20
lines changed

1 file changed

+13
-20
lines changed

2d/platformer/player.gd

Lines changed: 13 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -3,49 +3,42 @@ extends KinematicBody2D
33
const GRAVITY_VEC = Vector2(0, 900)
44
const FLOOR_NORMAL = Vector2(0, -1)
55
const SLOPE_SLIDE_STOP = 25.0
6-
const MIN_ONAIR_TIME = 0.1
76
const WALK_SPEED = 250 # pixels/sec
87
const JUMP_SPEED = 480
98
const SIDING_CHANGE_SPEED = 10
109
const BULLET_VELOCITY = 1000
1110
const SHOOT_TIME_SHOW_WEAPON = 0.2
1211

1312
var linear_vel = Vector2()
14-
var onair_time = 0 #
1513
var on_floor = false
16-
var shoot_time=99999 #time since last shot
14+
var shoot_time = 99999 # time since last shot
1715

18-
var anim=""
16+
var anim = ""
1917

20-
#cache the sprite here for fast access (we will set scale to flip it often)
18+
# cache the sprite here for fast access (we will set scale to flip it often)
2119
onready var sprite = $sprite
2220

2321
func _physics_process(delta):
24-
#increment counters
25-
26-
onair_time += delta
22+
# Increment counters
2723
shoot_time += delta
2824

2925
### MOVEMENT ###
3026

31-
# Apply Gravity
27+
# Apply gravity
3228
linear_vel += delta * GRAVITY_VEC
33-
# Move and Slide
29+
# Move and slide
3430
linear_vel = move_and_slide(linear_vel, FLOOR_NORMAL, SLOPE_SLIDE_STOP)
35-
# Detect Floor
36-
if is_on_floor():
37-
onair_time = 0
38-
39-
on_floor = onair_time < MIN_ONAIR_TIME
31+
# Detect if we are on floor - only works if called *after* move_and_slide
32+
var on_floor = is_on_floor()
4033

4134
### CONTROL ###
4235

43-
# Horizontal Movement
36+
# Horizontal movement
4437
var target_speed = 0
4538
if Input.is_action_pressed("move_left"):
46-
target_speed += -1
39+
target_speed -= 1
4740
if Input.is_action_pressed("move_right"):
48-
target_speed += 1
41+
target_speed += 1
4942

5043
target_speed *= WALK_SPEED
5144
linear_vel.x = lerp(linear_vel.x, target_speed, 0.1)
@@ -58,10 +51,10 @@ func _physics_process(delta):
5851
# Shooting
5952
if Input.is_action_just_pressed("shoot"):
6053
var bullet = preload("res://bullet.tscn").instance()
61-
bullet.position = $sprite/bullet_shoot.global_position #use node for shoot position
54+
bullet.position = $sprite/bullet_shoot.global_position # use node for shoot position
6255
bullet.linear_velocity = Vector2(sprite.scale.x * BULLET_VELOCITY, 0)
6356
bullet.add_collision_exception_with(self) # don't want player to collide with bullet
64-
get_parent().add_child(bullet) #don't want bullet to move with me, so add it as child of parent
57+
get_parent().add_child(bullet) # don't want bullet to move with me, so add it as child of parent
6558
$sound_shoot.play()
6659
shoot_time = 0
6760

0 commit comments

Comments
 (0)