Unity Touch Input

2075 / Unity / 2D / 3D / Touch Input

 

Game -> Simulator

 

Swipe

 

Змін світлини при проведенні пальцем

 

public Image slideImage;
public List<Sprite> images;

Vector2 startTouchPosition;
Vector2 endTouchPosition;

public int index = 0;

void Update()
{
  if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
  {
    startTouchPosition = Input.GetTouch(0).position;
  }

  if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Ended)
  {
    endTouchPosition = Input.GetTouch(0).position;
    if (endTouchPosition.x < startTouchPosition.x)
    {
      NextPage();
    }
    if (endTouchPosition.x > startTouchPosition.x)
    {
      PrivousPage();
    }
  }
}

void PrivousPage()
{
  index--;
  if (index < 0)
  {
    index = 0;
  }
  slideImage.sprite = images[index];
}

void NextPage()
{
  index++;
  if (index > images.Count - 1)
  {
    index = images.Count - 1;
  }
  slideImage.sprite = images[index];
}

 

 

MoveOneMeter

 

Рухати вліво / вправо на метр


Vector2 startTouchPosition;
Vector2 endTouchPosition;

void Update()
{
  if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
  {
    startTouchPosition = Input.GetTouch(0).position;
  }

  if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Ended)
  {
    endTouchPosition = Input.GetTouch(0).position;

    if (endTouchPosition.x < startTouchPosition.x)
    {
      Left();
    }
    if (endTouchPosition.x > startTouchPosition.x)
    {
      Right();
    }
  }
}

void Right()
{
  transform.position = new Vector3(transform.position.x + 1, transform.position.y, transform.position.z);
}

void Left()
{
  transform.position = new Vector3(transform.position.x - 1, transform.position.y, transform.position.z);
}



MoveOffsetMouse2D

Рух за мишею (на відстані)

public Rigidbody2D rb;
float deltaX;
float deltaY;

void Update()
{
  if (Input.touchCount > 0)
  {
    Touch touch = Input.GetTouch(0);
    Vector2 touchPos = Camera.main.ScreenToWorldPoint(touch.position);
    switch (touch.phase)
    {
      case TouchPhase.Began:
        deltaX = touchPos.x - transform.position.x;
        deltaY = touchPos.y - transform.position.y;
        break;
      case TouchPhase.Moved:
        rb.MovePosition(new Vector2(touchPos.x - deltaX, touchPos.y - deltaY));
        break;
      case TouchPhase.Ended:
        rb.velocity = Vector2.zero;
        break;
    }
  }
}