I am developing endless runner game like subway surfer in Unity.
I want to move my player, smoothly on swipe left or right.
How can do it?
Here is my code:
using UnityEngine;
using System.Collections;
public class SwipeScript3 : MonoBehaviour {
private Touch initialTouch = new Touch();
private float distance = 0;
private bool hasSwiped = false;
//Quaternion targetx = Quaternion.Euler(0, -3f, 0);
//Quaternion targety = Quaternion.Euler(0, 3f, 0);
void FixedUpdate()
{
foreach(Touch t in Input.touches)
{
if (t.phase == TouchPhase.Began)
{
initialTouch = t;
}
else if (t.phase == TouchPhase.Moved && !hasSwiped)
{
float deltaX = initialTouch.position.x - t.position.x;
float deltaY = initialTouch.position.y - t.position.y;
distance = Mathf.Sqrt((deltaX * deltaX) + (deltaY * deltaY));
bool swipedSideways = Mathf.Abs(deltaX) > Mathf.Abs(deltaY);
if (distance > 50f)
{
if (swipedSideways && deltaX > 0) //swiped left
{
//transform.rotation = Quaternion.Slerp (transform.rotation, targetx, Time.deltaTime * 0.8f);
this.transform.Rotate(new Vector3(0, -3f, 0)*Time.deltaTime);
//transform.position = Vector3.Lerp (transform.position,new Vector3(transform.position.x+5f,transform.position.y,transform.position.z),Time.deltaTime*2f );
transform.position = Vector3.Lerp (transform.position, new Vector3 (transform.position.x - 5f, transform.position.y, transform.position.z), Time.deltaTime * 5f);
}
else if (swipedSideways && deltaX <= 0) //swiped right
{
//transform.rotation = Quaternion.Slerp (transform.rotation, targety, Time.deltaTime * 0.8f);
this.transform.Rotate(new Vector3(0, 3f, 0)*Time.deltaTime);
//transform.position = Vector3.Lerp (transform.position, new Vector3 (transform.position.x - 5f, transform.position.y, transform.position.z), Time.deltaTime * f);
transform.position = Vector3.Lerp (transform.position,new Vector3(transform.position.x+5f,transform.position.y,transform.position.z),Time.deltaTime*5f );
}
else if (!swipedSideways && deltaY > 0) //swiped down
{
//this.transform.Rotate(new Vector3(0, 2f, 0));
transform.position = Vector3.Lerp (transform.position,new Vector3(transform.position.x,transform.position.y,transform.position.z-5f),Time.deltaTime*2f );
}
else if (!swipedSideways && deltaY <= 0) //swiped up
{
this.GetComponent<Rigidbody>().velocity = new Vector3(this.GetComponent<Rigidbody>().velocity.x, 0, this.GetComponent<Rigidbody>().velocity.z);
this.GetComponent<Rigidbody>().AddForce(new Vector3(0, 400f, 0));
Debug.Log ("Swiped Up");
}
hasSwiped = true;
}
}
else if (t.phase == TouchPhase.Ended)
{
initialTouch = new Touch();
hasSwiped = false;
}
}
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…