简体   繁体   中英

How can I make my character move when slide in Unity?

I would like make my character move to the left or to the right when slide the screen or touch a virtual button in a phone for Unity 3D, this is the player's script of the movement to move it with the keyboard keys, but I would like it to be for mobile.

void FixedUpdate ()
{
    // Add a forward force
    rb.AddForce(0, 0, forwardForce * Time.deltaTime);

    if (Input.GetKey("d"))  // If the player is pressing the "d" key
    {
        // Add a force to the right
        rb.AddForce(sidewaysForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
    }

    if (Input.GetKey("a"))  // If the player is pressing the "a" key
    {
        // Add a force to the left
        rb.AddForce(-sidewaysForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
    }

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

}

Most basic way to handle this would be (I think) something along the lines of:

float lastPosition;
void OnSwipte(float delta)
{
// code your movement here
}
void Update()
{
 if (Input.GetMouseButtonDown(0)) 
       lastPosition=Input.mousePosition.x; // store touch point
  else 
  if (Input.GetMouseButton(0)) 
    {
     OnSwipe(Input.mousePosition.x-lastPosition);
     lastPosition=Input.mousePosition.x; 
    }
   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM