Change tiles while left mouse button is clicked and the cursor is hovering over the tile

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

Hello!

As stated in the title, I’m trying to make it so that the tiles change when the mouse hovers over them while the left mouse button is clicked. At first, I thought that I’m close to the solution with this code:

const BLACK = 0
const WHITE = 2
const RING = 3
const GRAY = 4
const GREEN = 5
const RING_GREEN = 6
const BLACK_GREEN = 7

func _unhandled_input(event):
	if event is InputEventMouseButton:
		if event.button_index == BUTTON_LEFT and event.pressed:
			var clicked_cell = world_to_map(event.position)
			var color_check = self.get_cellv(clicked_cell)
			match color_check:
				WHITE:
					self.set_cellv(clicked_cell, GREEN)
				BLACK:
					self.set_cellv(clicked_cell, BLACK_GREEN)
				RING:
					self.set_cellv(clicked_cell, RING_GREEN)
				GREEN:
					self.set_cellv(clicked_cell, WHITE)
				BLACK_GREEN:
					self.set_cellv(clicked_cell, BLACK)
				RING_GREEN:
					self.set_cellv(clicked_cell, RING)

But while this code works great for one click, it doesn’t to anything when the left mouse button is already pressed. Because of that, I then proceeded to try to get a similar function to work in the process function using
if Input.is_mouse_button_pressed(BUTTON_LEFT):, but I always failed to get the “world_to_map” function to work with that.

I don’t know how to achieve my goal anymore at this point and hope that somebody here can help me.^^’

:bust_in_silhouette: Reply From: jgodfrey

Completely untested, but I might try to track the state of the mouse button in the _input() handler, and then use that in _process() to do the cell checking / updating. So, something like:

var mouse_button_pressed = false

func _input(event):
	if event is InputEventMouseButton:
		if event.button_index == BUTTON_LEFT and event.is_pressed():  
			mouse_button_pressed = true
		elif not event.is_pressed():  # Mouse button released.
			mouse_button_pressed = false

func _process(delta):
	if mouse_button_pressed:
        var mouse_position = get_viewport().get_mouse_position()
        # move much of your code here...

Then, move much of your “cell processing” code to the end of the above, where the comment is. And, use the new mouse_position variable in place of event.position from your original code.

Thank you!! This worked great! I now have to see how to give it a short cooldown, but I think that I’ll be able to do that myself, be it with a bit of google-fu. My idea for now is to do that with a timer node. If I don’t get it to work, I’ll have to return to this forum. Maybe a nice person will help me again. For now thank you for your help again and have a nice day!

Izaro | 2023-01-16 22:58