- Home /
Touchscreen Movement on buttons
I am building a game on android (clone of space invaders 2D). So the ship has to move only left and right in 2D. I don't want to use a joystick, I want buttons for better phone experience. This is my moving algorithm for the same game, PC version. Please help, I couldn't find anything useful on internet that works for me. How can I implement touchscreen button control on this?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Spaceship : MonoBehaviour
{
public float speed = 30;
public GameObject theBullet;
void FixedUpdate()
{
float horzMove = Input.GetAxisRaw("Horizontal");
GetComponent<Rigidbody2D>().velocity = new Vector2(horzMove, 0) * speed;
}
// Update is called once per frame
void Update()
{
if(Input.GetButtonDown("SpaceShipShoot"))
{
Instantiate(theBullet, transform.position, Quaternion.identity);
soundManager.Instance.playOneShot(soundManager.Instance.BulletFire);
}
}
}
Answer by Llama_w_2Ls · Aug 19, 2020 at 07:53 PM
Well first of all, i wouldnt want to be getting the Rigidbody2D every frame as thats quite unnecessary and not very CPU mobile friendly. Secondly, you can have two public functions, one for moving left and right, which happen on button press. For example:
Rigidbody2D rb2D;
public float speed = 30f;
private void Start()
{
rb2D = GetComponent<Rigidbody2D>();
}
public void MoveLeft()
{
rb2D.velocity = new Vector2(-1, 0) * speed;
}
public void MoveRight()
{
rb2D.velocity = new Vector2(1, 0) * speed;
}
@TheNucleaLion (im assuming youve worked with UI Buttons before, right?)
@Llama_w_2Ls yes, I did work. I mostly used them for menus(pause, main menu, death scene etc) and other UI. I will try right now your algorithm and will answer after that
@Llama_w_2Ls I also got a problem with the unity placement part. Should I attach the spaceship in the same canvas as the buttons?
No, you dont have to do that, but on the UI button, you need to reference the script that the spaceship contains, and reference it inside of the onValueChanged() section of the button in the inspector, then search for the right function in the dropdown. Theres a few tutorials on UI scripting available on youtube
@Llama_w_2Ls okk, got this, now it's working. I still got only one more issue: after releasing the button, the spaceship doesn't stop, it keeps going left/right until the other button is pressed. How can I fix it?
Your answer
![](https://koobas.hobune.stream/wayback/20220613010043im_/https://answers.unity.com/themes/thub/images/avi.jpg)