- Home /
follow touch input whist falling
hey everyone just so you know I'm a beginner
Ive been driving myself mad trying to make a touch script. I'm aiming for something along the lines of making the player follow your touch input in the x axis whilst falling.
I've managed to get it working apart from i need to make the flip sprite a little less sensitive and i need to only allow one touch because if i touch the screen by accident it messes up the movement.
i have watched a lot of tutorials and tried my best to build my own script to fit my needs but still need help.
also is there a more efficient way or is they way i have done this ok?
public class TouchPad : MonoBehaviour, IPointerDownHandler, IDragHandler, IPointerUpHandler {
public float minX = -2.5f;
public static float moveToX;
private bool touched;
private int pointerID;
void Awake ()
{
moveToX = 0;
touched = false;
}
public void OnPointerDown (PointerEventData data)
{
if (!touched)
{
touched = true;
pointerID = data.pointerId;
}
}
public void OnDrag (PointerEventData data)
{
if (data.pointerId == pointerID)
{
moveToX = minX + (minX * -2) * data.position.x / Screen.width;
// moveToX = x;
}
}
public void OnPointerUp (PointerEventData data)
{
if (data.pointerId == pointerID)
{
touched = false;
}
}
}
and
public class PlayerControl : MonoBehaviour { public static float speed = 4f; bool facingRight = true;
void FixedUpdate ()
{
GameControl.dist = (int) Mathf.Abs(transform.position.y);
float x = transform.position.x;
float y = transform.position.y;
Vector2 currentPos = new Vector2(x, y);
Vector2 targetPos = new Vector2 (TouchPad.moveToX, y);
transform.position = Vector2.MoveTowards(currentPos, targetPos, speed * Time.deltaTime);
if(TouchPad.moveToX > (currentPos.x + 0.01) && !facingRight)
Flip ();
else if (TouchPad.moveToX < (currentPos.x - 0.01) && facingRight)
Flip ();
}
void Flip()
{
facingRight = !facingRight;
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
public void SpeedRange (float newSpeed)
{
speed = newSpeed;
}
}
Your answer
Follow this Question
Related Questions
Touch position is off screen. 1 Answer
unify touch position with player position 1 Answer
Object following mouse touch on distance 1 Answer