Question by
dvoracekm6 · Apr 19, 2019 at 08:35 PM ·
2d gameswipeflip
How to swipe only once while the action is still running?
Hi, I am new to Unity and trying to build my first android game through youtube videos and tutorials on the internet. Now I have problem and don't know how to solve it. Right now I am writing script for the player character. I want to move him from left and right when I swipe on screen. It is working, kind off.
My problems are:
I can swipe more than once while it is still moving. Really don't want that to happen.
The character is flipping from left to right spontaneously at the start untill I touch the screen. Then it is okay. I want him to facing right at the start.
Here is my code: Any help would be highly appreciated.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SmoothMoveSwipe : MonoBehaviour {
private Rigidbody2D myrigidbody;
private bool facingright;
private float Horizontal;
private Vector2 startTouchPosition, endTouchPosition;
private Vector3 startRocketPosition, endRocketPosition;
private float flyTime;
private float flightDuration = 0.1f;
// Start is called before the first frame update
void Start()
{
facingright = true;
myrigidbody = GetComponent<Rigidbody2D>();
}
private void FixedUpdate()
{
Flip();
}
// Update is called once per frame
private void Update()
{
if (Input.touchCount == 1 && Input.GetTouch(0).phase == TouchPhase.Began)
startTouchPosition = Input.GetTouch(0).position;
if (Input.touchCount == 1 && Input.GetTouch(0).phase == TouchPhase.Ended)
{
endTouchPosition = Input.GetTouch(0).position;
if ((endTouchPosition.x < startTouchPosition.x) && transform.position.x > -1.5f)
StartCoroutine(Fly("left"));
if ((endTouchPosition.x > startTouchPosition.x) && transform.position.x < 1.5f)
StartCoroutine(Fly("right"));
}
float move = Input.GetAxis("Horizontal");
if (endTouchPosition.x < startTouchPosition.x && facingright) Flip();
if (endTouchPosition.x > startTouchPosition.x && !facingright) Flip();
}
private IEnumerator Fly(string whereToFly)
{
switch (whereToFly)
{
case "left":
flyTime = 0f;
startRocketPosition = transform.position;
endRocketPosition = new Vector3
(startRocketPosition.x - 1f, transform.position.y);
while (flyTime < flightDuration)
{
flyTime += Time.deltaTime;
transform.position = Vector2.Lerp
(startRocketPosition, endRocketPosition, flyTime / flightDuration);
yield return null;
}
break;
case "right":
flyTime = 0f;
startRocketPosition = transform.position;
endRocketPosition = new Vector3
(startRocketPosition.x + 1f, transform.position.y);
while (flyTime < flightDuration)
{
flyTime += Time.deltaTime;
transform.position = Vector2.Lerp
(startRocketPosition, endRocketPosition, flyTime / flightDuration);
yield return null;
}
break;
}
}
private void Flip()
{
facingright = !facingright;
transform.Rotate(Vector3.up * 180);
}
}
Comment