How can I code a weapon switch based of proximity torwards the enemy instead of input (button press)?

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

Hi all,

I am new to programming and I would like to make a game that consist of using a melee (knife) and range weapon( bow and arrow). The way the melee weapon is triggered is by being close to the enemy at a certain proximity which will auto switch to the melee weapon and switch back to the range weapon once you step away from that proximity.

Any help is greatly appreciate, and hope you all stay safe with the pandemic.

Thanks!

:bust_in_silhouette: Reply From: RazorSh4rk

You can use something like this, but your question is very vague, we can help more after youve started working on your game

func get_dist(from, to):
    return sqrt(pow(to.position.x - from.position.x, 2) + pow(to.position.y - from.position.y, 2))

func _process(delta):
    if(get_dist($player, $enemy) < 50):
	    weapon = 'knife'
    else:
	    weapon = 'gun'

    print(weapon)

Or you could just add a sphere collider to the enemy and check when the player enters/exits the collider. Not sure if this would cost performance or not, but either way it would probably be to small to count.

Millard | 2020-05-15 00:46

I was not expecting an answer, any answer really, especially today. Thanks RazorSh4rk! I wish I could be more specific with the question, I guess I will learn as I go and get more used to the coding lingo. I will give this a try thanks again.

Nelson L Nieves | 2020-05-15 03:23