- Home /
How do I effectively use UI buttons to move my character without confusing assets from the asset store?
Howdy! I am making a mobile game and I am having a slight problem with my code and movement for my character, whenever I tap the screen, he always goes a little further than he's supposed to, like he's on wheels or something. I have searched many tutorials and none of them can seem to fix my problem, without using some complicated asset from the asset store. I have my code and a link to a gif below (if the link doesn't work, its just me tapping on the screen, my character moving, and then I let go/ don't touch the screen and he continues to move for a short period of time, and then stopping, again like he's on wheels). Anyways, thank you to anyone who helps me with this, its been a pain in my side for most of my development and I would really like to move on from it, thanks!
Code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerControls : MonoBehaviour {
public float speed;
public float jumpForce;
private Rigidbody2D rb;
private float ScreenWidth;
private bool facingRight = true;
void Start()
{
ScreenWidth = Screen.width;
rb = GetComponent<Rigidbody2D> ();
}
void Update()
{
int i = 0;
while (i < Input.touchCount) {
if (Input.GetTouch (i).position.x > ScreenWidth / 4) {
//move right, supposedly
RunCharacter (1.0f);
}
if (Input.GetTouch (i).position.x < ScreenWidth / 4) {
//move left, supposedly
RunCharacter (-1.0f);
}
++i;
}
}
void RunCharacter(float horizontalInput)
{
rb.AddForce (new Vector2 (horizontalInput * speed, rb.velocity.y));
}
void Flip()
{
facingRight = !facingRight;
Vector3 Scaler = transform.localScale;
Scaler.x *= -1;
transform.localScale = Scaler;
}
}