I just wrapped up a remote presentation at Ivy Tech in which I gave an introduction to game design and development. The presentation included a roughly one-and-a-half-hour workshop on Godot Engine. We built the start of a no-frills platformer from scratch. Unfortunately, there was a little, non-obvious bug in that moving to the left caused the animation to flip out. What makes that worthy of blogging? Well, I told them I'd post the fix on my blog, so here we go!
This was the original implementation of Player.gd:
extends KinematicBody2D
var speed = 200
var gravity = 10
var velocity = Vector2(0,0)
func _physics_process(delta):
velocity.y = velocity.y + gravity
var direction = Vector2(0,0)
if Input.is_action_pressed("move_right"):
direction.x = 1
$AnimatedSprite.play("walk")
scale.x = 1
elif Input.is_action_pressed("move_left"):
direction.x = -1
scale.x = -1
$AnimatedSprite.play("walk")
else:
$AnimatedSprite.play("default")
if Input.is_action_just_pressed("jump"):
velocity.y = -500
velocity.x = direction.x * speed
move_and_slide(velocity, Vector2.UP)
The problem is clearly with scale.x because nothing else would make it flip out like that. The solution is to scale not the whole object but just the sprite. Once I realized that, the fix was easy. Here's the revised version.
extends KinematicBody2D
var speed = 200
var gravity = 10
var velocity = Vector2(0,0)
func _physics_process(delta):
velocity.y = velocity.y + gravity
var direction = Vector2(0,0)
if Input.is_action_pressed("move_right"):
direction.x = 1
$AnimatedSprite.play("walk")
$AnimatedSprite.scale.x = 1
elif Input.is_action_pressed("move_left"):
direction.x = -1
$AnimatedSprite.scale.x = -1
$AnimatedSprite.play("walk")
else:
$AnimatedSprite.play("default")
if Input.is_action_just_pressed("jump"):
velocity.y = -500
velocity.x = direction.x * speed
move_and_slide(velocity, Vector2.UP)
Fixing bugs like this while livecoding is like doing elementary arithmetic at the front of the room while holding a marker. That part of the brain just shuts down.
No comments:
Post a Comment