- Home /
Question by
Virdari · Aug 13, 2014 at 09:52 PM ·
2drigidbody2dvelocityswipe
issue with moving GameObject consistently
So here is what i'm trying to do: MainPlayer will run upwards endlessly, when there is a swipe from left to right or right to left he will switch lanes. Here is the code for mainplayer:
using UnityEngine;
using System.Collections;
public class CharTouchCont: MonoBehaviour
{
public float moveSpeed = 3f;
public float swipeVelocity = 9f;
public float timeThreshold = 0.35f;
// swipe related variables
private bool canSwipe;
private Vector2 startPosition;
private Vector2 endPosition;
void Start ()
{
canSwipe = true;
}
void Update ()
{
rigidbody2D.velocity = new Vector2 (0, moveSpeed);
if (Input.touchCount == 1 && Input.GetTouch (0).phase == TouchPhase.Ended && canSwipe == true) // End of Touch
{
canSwipe = false;
endPosition = Input.GetTouch (0).position;
if (startPosition.x < endPosition.x) // left to right swipe
{
rigidbody2D.velocity = new Vector2 (swipeVelocity, rigidbody2D.velocity.y);
StartCoroutine ("delay");
}
else if (endPosition.x < startPosition.x) // right to left swipe
{
rigidbody2D.velocity = new Vector2 (-swipeVelocity, rigidbody2D.velocity.y);
StartCoroutine ("delay");
}
}
if (Input.touchCount == 1 && Input.GetTouch (0).phase == TouchPhase.Began && canSwipe == true) // Start of Touch
startPosition = Input.GetTouch (0).position;
if (Input.GetKey (KeyCode.Escape))
Application.Quit ();
}
IEnumerator delay ()
{
yield return new WaitForSeconds (timeThreshold);
rigidbody2D.velocity = new Vector2 (0, rigidbody2D.velocity.y);
canSwipe = true;
}
}
i'm trying to move him to left or right by increasing the velocity in x axis by 9 for 0.35 seconds and then setting it back to 0. so i will move left to right depending on swipe by 3.15 units ( 9 * 0.35) the issue is that after i run the game my character starts to stop at positions which are slightly to the left or right of where he should be or sometimes in between 2 lanes. How do i make it so that my GameObject will move 3.15 units to left or right consistently?
Comment