Begginer here using Godot Engine 3.5.2. I want to detect if the player clicks on the enemy image.
The enemy is composed of a Node2D that has an AnimatedSprite as a child, which is responsible for representing the enemy on the screen by playing the enemy's animations. So when the player clicks, I need to detect which image is being played by the AnimatedSprite and if the enemy is drawn at the mouse position, that is, avoiding detecting the enemy if the player clicks on the transparent area of the enemy image.
The hardest part for me is calculating the position of the image on the screen, since all of these variables can change during the game and influence it:
The scale and position values of the Node2D can vary.
The scale, position, offset, and flip_h values of the AnimatedSprite can vary.
I would also have to take into accound that the value of the centered property of the AnimatedSprite is always set to "1" or "True". That doesn't change.
I have tried all day with no success. This is the latest code I've tried, that is able to detect the enemy (opaque pixels), the transparent pixels and the "out of sprite" clicks but everything in the wrong positions:
var mouse_pos = get_global_mouse_position()
var local_pos = enemy_animated_sprite.get_parent().to_local(mouse_pos)
var enemy_pos = enemy_animated_sprite.get_global_transform().xform_inv(local_pos)
var size = enemy_animated_sprite.frames.get_frame(enemy_animated_sprite.animation, enemy_animated_sprite.frame).get_size()
var pos = enemy_animated_sprite.offset
if enemy_animated_sprite.centered:
pos -= 0.5 * size
var frame_rect = Rect2(pos, size)
if frame_rect.has_point(enemy_pos):
var frame_texture = enemy_animated_sprite.frames.get_frame(enemy_animated_sprite.animation, enemy_animated_sprite.frame)
var frame_image = frame_texture.get_data()
frame_image.lock()
var pixel_pos = enemy_pos - pos
var parent_scale = enemy_animated_sprite.get_parent().get_scale()
var enemy_scale = enemy_animated_sprite.get_scale()
pixel_pos.x /= parent_scale.x * enemy_scale.x
pixel_pos.y /= parent_scale.y * enemy_scale.y
if enemy_animated_sprite.flip_h:
pixel_pos.x = size.x - pixel_pos.x
var pixel_color = frame_image.get_pixel(pixel_pos.x, pixel_pos.y)
frame_image.unlock()
if pixel_color.a > 0:
print("CLICKED ON ENEMY")
else:
print("clicked on transparent part of sprite")
else:
print("clicked out of sprite")
pass