← Pixel Dreamer Studio

Block only attacks from the front

Normalize both directions, flat on the ground, before the dot product.

Flatten the direction to the attacker onto the ground, normalize it and the character's forward direction, and compare their dot product with the cosine of your block angle. Without normalizing, the dot product grows with distance: in our Godot 4.7 test a check of dot > 0.5 blocked an attacker 5 m away at 80 degrees to the side, and did not block one straight ahead at 0.4 m. The script below, with a 60 degree block angle, gave the expected answer at all seven positions we tried.

The code

Add this as a child of the character, which should face -Z, Godot's forward. When a hit lands, call can_block(attacker.global_position) and play your block effect instead of the hit if it returns true.

extends Node3D
## Lets a character block only hits that come from in front of it.
## Add it as a child of the character (facing -Z, Godot's forward) and call can_block(attacker_position).

@export var block_angle := 60.0  ## degrees to either side of straight ahead


func can_block(from: Vector3) -> bool:
	var to := from - global_position
	to.y = 0.0  # compare on the ground, so an attacker on a ledge still counts as in front
	if to.length() < 0.001:
		return true
	var ahead := -global_basis.z
	ahead.y = 0.0
	# both directions normalized: the dot is then the cosine of the angle, whatever the distance
	return ahead.normalized().dot(to.normalized()) >= cos(deg_to_rad(block_angle))

What we measured

A character at the origin facing -Z, blocking up to 60 degrees to either side.

Two runs gave the same answers.

Why normalizing matters

The dot product of two directions is their lengths multiplied together and by the cosine of the angle between them. If the direction to the attacker is not normalized, its length is the distance, so a far attacker at a wide angle passes a check meant for a narrow one, and a very close attacker straight ahead fails it. Normalized, the dot product is the cosine alone, so the same angle gives the same answer at any distance. Flattening the height first means the answer depends only on where the attacker stands around the character.

What to change

Ready-made block and parry effects: Combat Defense VFX for Godot 4 has 29 presets in Stylized and Retro PSX looks for souls-like and action games, including Parry Spark, Perfect Parry, Block Wood, Block Metal, a hex Block Magic shield and Guard Break, plus a 3D afterimage for dodges.

Tested in Godot 4.7 with the Compatibility renderer.

Ready-made: Combat Defense VFX for Godot 4 has 29 ready-made defensive combat effects in Stylized and Retro PSX looks, including Parry Spark, Perfect Parry, Block Wood, Block Metal, Block Magic and Guard Break.

More how-tos: Hazards, traps and attacks