Last active
July 31, 2020 01:25
-
-
Save kenmorechalfant/c875c08228e1f28129a1ea4e7a740242 to your computer and use it in GitHub Desktop.
Basic 2d top down player movement
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extends Node | |
class_name MovementComponent | |
var updated_node: KinematicBody2D | |
var speed := 38 | |
var acceleration := 0.1 | |
var deceleration := 0.25 | |
var move_input := Vector2.ZERO | |
var last_move_input := Vector2.ZERO | |
var facing_direction := Vector2.UP | |
var velocity := Vector2.ZERO | |
var can_move := true | |
var is_stunned := false | |
func _ready(): | |
assert(owner is KinematicBody2D) | |
updated_node = owner | |
pass | |
# Have your Player/Enemy that this Node is attached to call this method to move | |
func add_movement_input(new_move_input: Vector2): | |
move_input = new_move_input | |
if not (move_input.is_equal_approx(Vector2.ZERO)): | |
facing_direction = move_input | |
# Clear the stored input vector and return its value | |
func consume_input()->Vector2: | |
var input = move_input | |
move_input = Vector2.ZERO | |
return input | |
func _physics_process(_delta): | |
var input = consume_input() | |
var interp_speed := acceleration if (input.length() > 0) else deceleration | |
velocity = lerp(velocity, input * speed, interp_speed) | |
#warning-ignore:return_value_discarded | |
owner.move_and_slide(velocity) | |
# Adds velocity in the opposite direction of an Origin | |
func knockback(origin: Vector2, amount: float): | |
velocity = (origin - owner.position).normalized() * amount * -1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment