- Home /
The question is answered, right answer was accepted
Why does my swiping code not work?
Hey, im new into Unity and coding and I wrote this code. It should let the player jump, if you swipe up (vertical) on a mobile device. Why does this not work? Sry for my bad english, if there are any mistakes. Im german. An answer would be very great.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Touch_Input : MonoBehaviour
{
public float jumpForce;
public float maxSwipeTime;
public float minSwipeTime;
public float MinSwipeDistance;
private float SwipeTime;
private float SwipeLength;
private float SwipeStartTime;
private float SwipeEndTime;
private Rigidbody2D rb;
private Vector2 SwipeStartPos;
private Vector2 SwipeEndPos;
private void Awake()
{
rb = GetComponent<Rigidbody2D>();
}
void swipeTest()
{
if (Input.touchCount > 0)
{
Touch touch = Input.GetTouch(0);
if (touch.phase == TouchPhase.Began)
{
SwipeStartTime = Time.time;
SwipeStartPos = touch.position;
}
else if (touch.phase == TouchPhase.Ended)
{
SwipeEndTime = Time.time;
SwipeEndPos = touch.position;
SwipeTime = SwipeEndTime - SwipeStartTime;
SwipeLength = (SwipeEndPos - SwipeStartPos).magnitude;
if (SwipeTime < maxSwipeTime && SwipeLength > MinSwipeDistance)
{
SwipeControl();
}
}
}
}
void SwipeControl()
{
Vector2 Distance = SwipeEndPos - SwipeStartPos;
float xDistance = Mathf.Abs(Distance.x);
float yDistance = Mathf.Abs(Distance.y);
float xDistance = Distance.x;
float yDistance = Distance.y;
if (Distance.x < Distance.y)
{
rb.velocity = new Vector2(rb.velocity.x, jumpForce);
}
} }
Have you tried testing with mouse and keyboard controls?
Answer by coding_frog · May 10, 2021 at 07:37 AM
Thank you so much for replying. If I remember correctly, yesterday it didn't work with the mouse and keyboard either. But I'll try again today, when I have time for it.
Try using debug.log() as well to add in messages so you know what part of your code is working or failing to work.
OK thanks. However, no error was displayed in the console yesterday. So it cannot be due to a wrong syntax. I can start the game as usual. Unfortunately, nothing happens when I swipe the screen. Is that the right thing to do with Debug.Log or did I do something wrong? Thanks again, that you are helping me.
So yes. you are using debug.log wrong. If that if statement works properly it will then put that string in the unity console when that part of the script gets called. Place a few of these and you can figure out what part is failing.
and if you wanted to know what a variable is you can do debug.Log(SwipeTime) which can let you know if your issue is that SwipeTime is never the right value.
if (SwipeTime < maxSwipeTime && SwipeLength > MinSwipeDistance)
{
debug.Log("SwipeControl is being called");
SwipeControl();
}