Hi to all, i’m very new on unity and i’m facing my first problem.
On my 3d project i have a spheric rigidbody that will rolling constantly along z (on a big square rigidbody used as “floor”), and i would like to translate it on x axis (left and right) with swipe.
This is the sphere controller script:
public class PlayerController : MonoBehaviour
{
public static PlayerController Instance { get; private set; }
private Rigidbody rb;
public float speed;
void Start()
{
Instance = this;
rb = GetComponent<Rigidbody>();
speed = 20f;
}
private void FixedUpdate()
{
rb.AddForce(0f, 0f, speed, ForceMode.Acceleration);
}
public void MovePlayer(float movement)
{
StartCoroutine(MovePlayerCoroutine(movement));
}
private IEnumerator MovePlayerCoroutine(float movement)
{
rb.position = new Vector3(
transform.position.x + (movement/ 20f),
transform.position.y,
transform.position.z);
yield return null;
}
(my rigidbody has mass, drag and angular drag 1, use gravity and interpolate).
this is the script (attached to Main Camera object) for detect left and righ swipe and move player:
public class SwipeController : MonoBehaviour
{
// detected position on last frame
private Vector3 lastTouchPosition;
// detected position on current frame
private Vector3 currentTouchPosition;
//minimum distance for a swipe to be detected
private float dragDistance;
void Start()
{
// dragDistance will be a portion of screen
dragDistance = Screen.width * 5 / 100;
}
private void Update()
{
foreach (Touch touch in Input.touches) //use loop to detect more than one swipe
{
if (touch.phase == TouchPhase.Began)
{
// first touch on screen
lastTouchPosition = touch.position;
}
else if (touch.phase == TouchPhase.Moved)
{
currentTouchPosition = touch.position;
if (Mathf.Abs(currentTouchPosition.x - lastTouchPosition.x) > dragDistance || Mathf.Abs(currentTouchPosition.y - lastTouchPosition.y) > dragDistance)
{//It's a drag
PlayerController.Instance.MovePlayer(currentTouchPosition.x - lastTouchPosition.x);
if ((currentTouchPosition.x > lastTouchPosition.x))
{ //Right swipe
Debug.Log("Right Swipe");
lastTouchPosition = currentTouchPosition;
}
else
{ //Left swipe
Debug.Log("Left Swipe");
lastTouchPosition = currentTouchPosition;
}
}
}
else if (touch.phase == TouchPhase.Ended)
{
// reset positions
lastTouchPosition = currentTouchPosition = new Vector3();
}
}
}
}
This code works but the movement is not smooth (it seems that sphere jump directly on new position). Whats the problem?