Search Unity

  1. If you have experience with import & exporting custom (.unitypackage) packages, please help complete a survey (open until May 15, 2024).
    Dismiss Notice
  2. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice

How to Create a touch Button to move a player?

Discussion in 'General Discussion' started by AlhasanY, Feb 10, 2020.

  1. AlhasanY

    AlhasanY

    Joined:
    Feb 10, 2020
    Posts:
    1
    Hello People,

    I am new to unity. I have build a game where there is a cube moving forward in the z-axis. The cube moves right and left to avoid colliding with obstacles. The game runs smooth when pressing Keyboard key buttons. But when I create buttons for my android phone it doesn't works correctly. When I create an event trigger for a button with (Pointer Down) and run the code, the cube will turn left when I constantly tap on the button. I have to tap 10 times in a second for it to turn right or left. I want it to be similar to the keyboard buttons where i press the button one time and everything moves smoothly. For the button event (Pointer Down) I have created this code

    public Rigidbody rb;
    public float forwardForce = 2000f;
    public float sidewayForce = 500f;

    public void Right()
    {
    rb.AddForce(sidewayForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
    }
    public void Left()
    {
    rb.AddForce(-sidewayForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
    }

    Here is my full player movement code:

    using UnityEngine.UI;
    using UnityEngine;
    public class PlayerMovement : MonoBehaviour
    {
    public Rigidbody rb;
    public float forwardForce = 2000f;
    public float sidewayForce = 500f;

    // Start is called before the first frame update
    public void Right()
    {
    rb.AddForce(sidewayForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
    }
    public void Left()
    {
    rb.AddForce(-sidewayForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
    }


    // Update is called once per frame
    void FixedUpdate ()
    {
    rb.AddForce(0, 0, forwardForce * Time.deltaTime);
    if(Input.GetKey("d"))
    {
    rb.AddForce(sidewayForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
    }
    if (Input.GetKey("a"))
    {
    rb.AddForce(-sidewayForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
    }

    if (rb.position.y < -1f)
    {
    FindObjectOfType<GameManager>().EndGame();
    }
    }
    }
     
  2. neginfinity

    neginfinity

    Joined:
    Jan 27, 2013
    Posts:
    13,604