Skip to content

Commit

Permalink
feat(smooth_movement): 添加 smooth_movement 类
Browse files Browse the repository at this point in the history
smooth_movement 可用于维护平滑移动的坐标。
  • Loading branch information
cutekibry committed Feb 18, 2024
1 parent 9073a7e commit 277dd06
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
45 changes: 45 additions & 0 deletions scripts/smooth_movement/smooth_movement.gd
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
class_name SmoothMovement extends Timer

var last_position := Vector2.ZERO
var target_position := Vector2.ZERO


enum SmoothType {
LINEAR,
QUAD_FADE_OUT,
SMOOTH_STEP,
}

@export var smooth_type := SmoothType.LINEAR


static func smooth_step(v1: Vector2, v2: Vector2, t: float) -> Vector2:
var t1 := t * t
var t2 := 1.0 - (1.0 - t) * (1.0 - t)
return v1.lerp(v2, lerpf(t1, t2, t))

static func quad_fade_out(v1: Vector2, v2: Vector2, t: float) -> Vector2:
return v1.lerp(v2, 1.0 - (1.0 - t) * (1.0 - t))


func set_position(position: Vector2):
self.last_position = position
self.target_position = position


func move_to(target_pos: Vector2, time: float) -> void:
self.last_position = self.target_position
self.target_position = target_pos
self.start(time)

func get_position() -> Vector2:
var t := 1.0 - self.time_left / self.wait_time
match self.smooth_type:
SmoothType.LINEAR:
return self.last_position.lerp(self.target_position, t)
SmoothType.QUAD_FADE_OUT:
return SmoothMovement.quad_fade_out(self.last_position, self.target_position, t)
SmoothType.SMOOTH_STEP:
return SmoothMovement.smooth_step(self.last_position, self.target_position, t)
return Vector2.ZERO

7 changes: 7 additions & 0 deletions scripts/smooth_movement/smooth_movement.tscn
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
[gd_scene load_steps=2 format=3 uid="uid://fxcs5dmb21q2"]

[ext_resource type="Script" path="res://scripts/smooth_movement/smooth_movement.gd" id="1_88rjn"]

[node name="SmoothMovement" type="Timer"]
one_shot = true
script = ExtResource("1_88rjn")

0 comments on commit 277dd06

Please sign in to comment.