I am trying make a functionality to my game so that the object with containerTransform can move 720f left or right depending upon the touch inputs. I have used Vector3.MoveTowards() but, it shows a **glitchy back and forth movement whenever I swipe right or left, instead of proper transition 720f right or left. I am not sure where my logic went wrong. Here are the complete codes. I am seeking your help. Thank you
private Vector2 startPosition;
private Vector2 endPosition;
public Transform containerTransform;
public float speed;
public float SoftZone = 20f;
//soft zone is the distance upto which the swipe wont work, so swipe length less than it wont trigger the function;
private bool SwipeLeft;
private bool SwipeRight;
private bool boolean;
private Vector3 currentLocation;
private Vector3 endLocation;
void Start()
{
currentLocation = containerTransform.position;
endLocation = containerTransform.position;
}
void Update()
{
if(SwipeLeft) {
containerTransform.position = Vector3.MoveTowards(
currentLocation,
endLocation,
Time.deltaTime * speed
);
if(containerTransform.position == endLocation) {
SwipeLeft = false;
currentLocation = endLocation;
print("swipeleft ends");
}
}
if(SwipeRight) {
containerTransform.position = Vector3.MoveTowards(
currentLocation,
endLocation,
Time.deltaTime * speed
);
if(containerTransform.position == endLocation) {
SwipeRight = false;
currentLocation = endLocation;
print("swiperight ends");
}
}
SwipeCheck ();
}
void SwipeCheck () {
/*if (!SwipeConfirmed){*/
foreach (Touch touch in Input.touches)
{
if(touch.phase == TouchPhase.Began)
{
startPosition = touch.position;
endPosition = touch.position;
boolean = true;
}
if (touch.phase == TouchPhase.Moved)
{
endPosition = touch.position;
}
if (touch.phase == TouchPhase.Ended ||
touch.phase == TouchPhase.Canceled &&
boolean == true)
{
if (startPosition.x - endPosition.x >= SoftZone)
{
SwipeLeft = true;
print("left");
endLocation += new Vector3(
endLocation.x - 720f,
endLocation.y,
endLocation.z
);
}
else if(startPosition.x - endPosition.x <= -SoftZone)
{
SwipeRight = true;
print("right");
endLocation += new Vector3(
endLocation.x + 720f,
endLocation.y,
endLocation.z
);
boolean = false;
}
}
}
}
MoveTowards
or with getting theVector3
from your swipe logic? A Minimal, Complete, and Verifiable would help here determining where your issue really is. I suggest code with debug statements showing your calculations and then copy-paste the output like code in your question. – Eliasar