- Home /
Touchscreen controls in a 2D game
Could you look into my code and tell me what I did wrong? I'm not an experienced programmer. Basically, the code should: 1.After touching the screen, he makes TouchPhase.Began location a point on screen using which we calculate the movement of an "on-screen joystick". With joystick, the player can go right and left 2. If player holds his finger on screen for 1,5 sec, his character is teleported to the location of his finger.
using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour {
public float speed ;
public float maxMovement ;
private float touchTime ;
// private Rigidbody2D rb;
void Start ()
{
// rb = GetComponent<Rigidbody2D>();
}
void FixedUpdate ()
{
if( Input.touchCount != 0 && Input.GetTouch (0) .phase == TouchPhase.Began)
{
Vector3 TouchCenter = new Vector3 (Input.GetTouch (0) .position.x , 0 );
//Vector3 maxMovement = new Vector3 ( maxMovement , 0 );
if( Input.GetTouch (0) .phase == TouchPhase.Moved)
{
Vector3 joystickMove = new Vector3 (Input.GetTouch (0) .position.x , 0 , 0);
Vector2 movement = new Vector2 (joystickMove.x - TouchCenter.x , 0);
if( movement.x >= maxMovement )
{
transform.Translate( maxMovement * speed , 0 , 0 );
if( Input.GetTouch (0) .phase == TouchPhase.Ended)
{
transform.Translate( - maxMovement * speed , 0 , 0 );
}else{
transform.Translate( maxMovement * speed, 0 , 0 );
}
if( Input.GetTouch (0) .phase == TouchPhase.Ended)
{
transform.Translate( - maxMovement * speed, 0 , 0 );
}
}
}
/*else if( Input.GetTouch(0) .phase != TouchPhase.Moved && Input.GetTouch (0) .deltaTime >= 1.5) That's that teleport thing
{
transform.position = TouchCenter ;
}*/
}
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613201156im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
iOS -Touch position unchanged, deltaPosition reported -1 Answers
Need a helping Hand: Dragging a rigidbody on touch move. 0 Answers
Touch Controls for a 2D ball game 0 Answers
How to reach limit line, keep moving, even past over the touch position? 0 Answers
Unity 2D - MoveTowards position not updating, not recgonizing new position 1 Answer