- 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;
}
}
Answer by Casiell · Jul 30, 2019 at 06:22 AM
AddForce method is the culprit here. While you are holding a finger on the screen you constantly add force to your characters Rigidbody subsequently increasing it's velocity. When you stop holding your finger, you stop adding force, but it doesn't mean that characters velocity disappeared.
You have three options: either set rb.velocity to Vector2.zero, or move the character by other methods, like rb.MovePosition. Third method is to increase your characters drag, that means it will lose velocity faster (but also gain it slower), in theory it's the worst out of three, because it doesn't solve your problem right away. But if you play around with Rigidbody2D settings in the inspector it's likely that you can tinker it so the effect is satisfying
Also what's up with your title? I can't figure out what does it have to do with your question?
Your answer
Follow this Question
Related Questions
How to make UI buttons so my player can move along certain lines 0 Answers
Button Navigation none - not working with touchscreen 0 Answers
Menu not getting Keyboard Input 0 Answers
AddListener function not working? 6 Answers
Touch input problem 1 Answer