How to stop the score counting upon hitting a block only once

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By steviecwheats

Hi there,
this is my first year upon using Godot and have came up with a brickbreaking game where the blocks change color (red>blue) upon being hit via setting the textures. This reduces the counter by -1 each time the ball makes contact with the red block that turns blue (ball not to be confused with the larger, round paddle). The game ends when all blocks are blue.

However, the counter should not be reduced when the ball hits any blue block and I could not come up with a solution. The following scripts use singletons between the global.gd and the brick.gd scripts where score and texture changes occur.

To sum up, the counter should -1 when red blocks turn blue and should not be registered on the ball hitting any blue block.

This is my global:

extends Node

var brick_counter = 0
var score = brick_counter
signal cleared_brick

func _ready():
  	pass
    
   func brick_changed():
 	score -= 1
	print(score)
	emit_signal("cleared_brick")
	if (score <= 0):
		print ("eat at Joe's")

And the brick script:

extends StaticBody2D

onready var area2d = get_node("Area2D")

var brick1 = load("res://sprites/brick.png")
var brick2 = load("res://sprites/brick_blue.png")
var texture_change = false
var score_stop = false

func _ready():
	Global.score += 1
	area2d.connect("body_entered", self, "_on_brick_body_entered")
		pass 

func _on_brick_body_entered(body):
	var mysprite = get_node("sprite")
	
#if the ball hit the brick, the brick changes from red to blue
	if body.get_name() == "ball":
			mysprite.set_texture(brick2)
			texture_change = true
			print ("ouch")
			Global.brick_changed()
#			brick_is_blue()
			#emit_signal("destroy", self)
			update()
	pass 

#func brick_is_blue():
#	if brick2:
#		Global.brick_counter = Global.score

Any help on this little project of mine will be greatly appreciated.

Maybe check for whether the color has changed on the brick, i.e.

 if not texture_change:
     Global.brick_changed()

If the color has already changed, the counter will only subtract the brick that was just changed.

Ertain | 2020-12-11 19:13

:bust_in_silhouette: Reply From: jgodfrey

Seems like you just need to set a flag when a block has been hit, and then don’t process any additional hits after the flag is set. So, something like this:

var hit = false # <---- add this flag

func _on_brick_body_entered(body):
    var mysprite = get_node("sprite")

    if body.get_name() == "ball":
        if !hit: # <--- If we haven't been hit yet, continue
            hit = true # <---- set the hit flag
            mysprite.set_texture(brick2)
            texture_change = true
            print ("ouch")
            Global.brick_changed()
            update()

Nice, it certainly works now with the extra flag. Much thanks to you.

steviecwheats | 2020-12-13 00:24