6 Adding Saw to the Game

Here we will implement the Saw to the game, its a moving obstracle for the player.

Here we will use the delta to move the object to and for.

We want the saw to move to and fro with different speed and variable lenght, thus we export the Speed, max left and max right.

@export var SPEED = 50;
@export var MAX_LEFT = 50;
@export var MAX_RIGHT = 60;

We encountered an error, where we tried to move the object itself, as the assign value is prespective to the parent. Then we update the code so we will move a child (visible stuffs)

func _process(delta):
	move(delta)
	pass

func move(delta):
	if moving_left:
		animated_sprite_2d.position.x -= SPEED * delta
		if animated_sprite_2d.position.x < -1 * MAX_LEFT:
			animated_sprite_2d.position.x = -1 * MAX_LEFT
			moving_left = false
	else:
		animated_sprite_2d.position.x += SPEED * delta
		if animated_sprite_2d.position.x > MAX_RIGHT:
			animated_sprite_2d.position.x = MAX_RIGHT
			moving_left = true
	pass

Now when a player touches the Saw, we call a function on that body (on player) and pass the direction it touched from.

func _on_area_2d_body_entered(body):
	var direction = 1
	if body.global_position.x < global_position.x:
		direction = -1
	body.hit(direction)