[Dive Into AGMaker] Plugin Release - Rotate GameObject to Point in the Direction of Movement Speed
License Agreement
You may freely use or modify this plugin in Action Game Maker for any purpose, whether for creating free or commercial projects. However, please do not redistribute it.
Credit is not necessary, but will be appreciated.
Plugin Effects
The name of this plugin is ArkAgmRotateToVelocity
. Its function is to rotate a game object every frame so that the “right side” of its local physics always points in the direction of its actual speed.
Key Points
- Requires specifying a
GameObject
. - You can specify a minimum effective speed squared value (using squared values is more efficient), and the script only activates when the actual speed exceeds this value.
- Supports two rotation modes: instant and smooth.
- In smooth mode, you can set a value to represent how fast the rotation occurs.
- The initial idea was to have a bullet object with an animation direction always pointing to the right, and with this script, it can rotate 360° according to the actual movement direction.
Core
Operation Steps
- Select the GameObject node.
- Press
Ctrl+A
to add a node of typeNode
, rename it toArkAgmRotateToVelocity
. - Select
ArkAgmRotateToVelocity
and add an empty GDscript. - Copy the entire script below and paste it into the script, then save.
- When the
ArkAgmRotateToVelocity
node is selected, you can adjust the parameters in the inspector as needed to decide whether to enable smooth rotation and other features.
Script
class_name ArkAgmRotateToVelocity extends Node
enum RotationMode {
INSTANT, # 立即旋转
SMOOTH, # 平滑旋转
}
@export var game_object: GameObject
@export var rotation_mode: RotationMode = RotationMode.INSTANT # 旋转模式
@export var rotation_speed: float = 5.0 # 旋转速度(当使用SMOOTH模式时使用)
@export var min_velocity_squared: float = 0.1 # 启动旋转的最小速度平方值
func _ready() -> void:
if not game_object:
# 尝试获取父节点作为game_object
var parent = get_parent()
if parent and parent is GameObject:
game_object = parent
else:
printerr("[ArkAgmRotateToVelocity] game_object is not set and parent is not a GameObject")
func _physics_process(delta: float) -> void:
if not game_object:
return
var velocity: Vector2 = game_object.get_real_velocity()
# 如果速度太小,不进行旋转
if velocity.length_squared() < min_velocity_squared:
return
# 计算目标角度(速度方向的角度)
var target_angle = velocity.angle()
match rotation_mode:
RotationMode.INSTANT:
# 立即旋转到目标角度
game_object.rotation = target_angle
RotationMode.SMOOTH:
# 平滑旋转到目标角度
var current_angle = game_object.rotation
var angle_diff = wrapf(target_angle - current_angle, -PI, PI)
game_object.rotation = current_angle + angle_diff * min(1.0, rotation_speed * delta)