【深入AGMaker】插件发布-旋转GameObject使其指向运动速度的方向

版权协议

你可以免费地在Action Game Maker中以任何目的使用或修改该插件,用于制作任何免费或是商用的项目。
但是请不要再分发它。署名不是必须的,但会受到感谢。

插件效果

这个插件的名字为ArkAgmRotateToVelocity
作用是每帧使一个游戏对象发生旋转,令其局部物理左边的“右侧”,总是指向自己实际速度的方向

要点

  • 需要指定GameObject
  • 可以指定一个最小生效速度的平方值(因为用平方值的话性能更加优秀),只有当实际速度大于这个值的时候,脚本功能才生效
  • 可以使用瞬间和平滑两种旋转模式
  • 平滑模式下可以设置一个值来代表旋转的有多块
  • 最初的想法是如果有一个动画方向总是指向右侧的子弹对象,那么配合这个脚本就可以做到360°根据实际运动方向来旋转方向了。

核心

操作步骤

  1. 选中GameObject节点
  2. Ctrl+A添加一个类型为Node的节点,改名为ArkAgmRotateToVelocity
  3. 选中ArkAgmRotateToVelocity,添加一个空的GDscript
  4. 把下方的脚本整个复制,贴到脚本中,保存。
  5. 当选中ArkAgmRotateToVelocity节点时。可以按需调整检查器上的参数。来决定是否开启平滑转动等功能。

脚本

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)