- Home /
player moving on the x axis with the finger does not work
Hey I'm developing an android game with unity its in 3d and the main point is that you are a square which you have to move on the x-Axis. I want that the player can place his finger wherever he wants and swipe left or right (still touching the display) and the distance between the positions where he starts touching and where he is now the square should move right or left. When the player is not touching it should not move at the x-Axis. I did this but my code has a problem when I release my finger and touch again without moving right or left the square deflects to one side very fast. Of course when the finger not move the square shouldn't move.
// My Code
public class PlayerMovement : MonoBehaviour
{
void FixedUpdate()
{
// move the player constantly forward
transform.position += Vector3.forward * Time.deltaTime * speed;
if (Input.touchCount > 0)
{
touch = Input.GetTouch(0);
// the current finger position
touchedPosMoved = Camera.main.ScreenToWorldPoint(new Vector3(touch.position.x, touch.position.y, 10));
switch (touch.phase)
{
case TouchPhase.Began:
// get finger position when touch start
touchedPosBegan = Camera.main.ScreenToWorldPoint(new Vector3(touch.position.x, touch.position.y, 10));
startX = transform.position.x;
break;
case TouchPhase.Moved:
// claculate the distance between start and curent position of the finger
differenz = Mathf.Abs(touchedPosBegan.x - touchedPosMoved.x);
if (touchedPosBegan.x > touchedPosMoved.x)
{
differenz = differenz * -1;
}
break;
}
// Move player at the X-axis
Vector3 idk = new Vector3((startX + differenz) * 8, transform.position.y, transform.position.z);
gameObjectStart = new Vector3(startX, transform.position.y, transform.position.z);
transform.position = Vector3.Lerp(gameObjectStart, idk, Time.deltaTime * 2);
}
}
}
Your answer
Follow this Question
Related Questions
Check whether touch is held 0 Answers
How to get intermediate swipe positions? 1 Answer
Unity Touch Help! 0 Answers
Reset touch Vector after movement 2 Answers
How to detect whether a particular touch has ended? 1 Answer