How can I make touch control for my game ?

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

Hello guys I have made a simple space shooter but the issue is that I made it for windows. I move using the WASD keys and fire using space key. But now I want to transfer it to android and I’m not sure how to handle touch input.

func _physics_process(delta):
	var dirVec = Vector2(0,0)
	$EngineFlame.process_material.tangential_accel = 0.0
	if Input.is_action_pressed("move_left"):
		$EngineFlame.process_material.tangential_accel = -150.0
		dirVec.x = -1
	elif Input.is_action_pressed("move_right"):
		$EngineFlame.process_material.tangential_accel = +150.0
		dirVec.x = 1
	if Input.is_action_pressed("move_up"):
		dirVec.y = -1
	elif Input.is_action_pressed("move_down"):
		dirVec.y = 1

I want the ship to keep firing as long as the person is touching the screen and want the ship to follow the finger where ever the person takes it. How can I do that ?

:bust_in_silhouette: Reply From: Magso

You can use InputEventScreenTouch to get the touch position. Because top left is the origin half of the screen size will have to be taken away to make the origin in the middle of the screen and then use normalized() so dirVec is a unit length of 1.

func _input(event):
    if event is InputEventScreenTouch:
        dirVec = (event.position - (get_viewport().size*0.5)).normalized()

Thanks for reply I got confused with the above so I used this instead of my above code :

var motionx=(get_global_mouse_position().x-position.x)*0.2
var motiony=(get_global_mouse_position().y-position.y)*0.2
translate(Vector2(motionx,motiony))

Now my player is following my mouse cursor. And I will assign the left mouse click to shoot action. Do you think now I can do something to make touch control easily ?

Edit : The game is working just fine on my phone and the player is moving just as I expected but he is not shooting. When I touch screen player follows my touch but I was expecting him to shoot also since I have assigned left click for shooting.

Scavex | 2020-09-08 06:35

You can either use a TouchScreenButton or make it fire automatically on an InputEventScreenTouch event.

Magso | 2020-09-08 08:26

func _input(event: InputEvent) -> void:
	if event is InputEventScreenDrag and fireDelayTimer.is_stopped():
		fire()
		print("Firing")
	pass

My player now fires when I keep my fingers moving but when I stop, no bullets get fired! I tried adding:

if event is InputEventScreenTouch and fireDelayTimer.is_stopped():
	fire()

he still doesn’t fire. But overall I am happy that at least he’s firing now when I keep my fingers moving.

Scavex | 2020-09-08 08:31

That’s because your using InputEventScreenDrag which provides a starting point and a relative drag point. InputEventSceenTouch will be active until you stop touching the screen, but this event doesn’t return a drag point.

Magso | 2020-09-08 08:52