- Home /
How to make Mobile Touch Controls work when pressing the left and right side of the screen
Hi there, I'm trying to create some basic movement mechanic for mobile where you press the left or right side of the screen to move the character. I managed to get it working using the horizontal input on pc but I can't work out how to do it on mobile. This is the player script I'm using:
public float speed;
private float ScreenWidth;
private Rigidbody2D rb;
private Vector2 moveVelocity;
// Use this for initialization
void Start () {
ScreenWidth = Screen.width;
rb = GetComponent<Rigidbody2D>();
}
void Update ()
{
// CONTROLLS FOR PC
Vector2 verticalMoveInput = new Vector2(Input.GetAxis("Horizontal"), 0);
moveVelocity = verticalMoveInput * speed;
int i = 0;
while(i < Input.touchCount)
{
if (Input.GetTouch(i).position.x > ScreenWidth / 2)
{
Debug.Log("WorkingRight");
// NEED TO MOVE RIGHT HERE
}
if(Input.GetTouch(i).position.x < ScreenWidth / 2)
{
Debug.Log("WorkingLeft");
// NEED TO MOVE LEFT HERE
}
++i;
}
}
private void FixedUpdate()
{
rb.MovePosition(rb.position + moveVelocity * Time.fixedDeltaTime);
if(rb.position.x >=3.1f)
{
playerAnim.SetTrigger("Death");
Destroy(gameObject, 0.9f);
}
if (rb.position.x <= -3.1f)
{
playerAnim.SetTrigger("Death");
Destroy(gameObject, 0.9f);
}
}
The controls work perfectly on pc so I want to know if there's a way of using the moving velocity or the verticalMoveInput to move the character when I press the left or right side of the screen. I hope this all makes sense to you ( I'm new to using touchscreen ) if anyone could help that would be great thanks.
Answer by Tsaras · Mar 02, 2019 at 04:18 PM
If I understand correctly, you want to find which code to place inside the ifs of the touch loops. You can go with:
int i = 0;
while(i < Input.touchCount)
{
if (Input.GetTouch(i).position.x > ScreenWidth / 2)
{
Debug.Log("WorkingRight");
moveVelocity = speed;
}
if(Input.GetTouch(i).position.x < ScreenWidth / 2)
{
Debug.Log("WorkingLeft");
moveVelocity = -speed;
}
++i;
}
You may want to add an acceleration factor to take you to max speed after a fraction of a second or so. Otherwise you are just getting a constant speed left or right.
Your answer
Follow this Question
Related Questions
How to move 2d object with touch anyscreen point 0 Answers
2½D Game’s Touch Camera Controls 0 Answers
I can't make drag and drop system work. 0 Answers
How to convert mouse input to mobile touch in unity 1 Answer
Multiple Cars not working 1 Answer