Skip to content

Instantly share code, notes, and snippets.

@nazmulkp
Created September 8, 2018 06:29
Show Gist options
  • Save nazmulkp/37f13af7b29324ebd2211e4423c417fc to your computer and use it in GitHub Desktop.
Save nazmulkp/37f13af7b29324ebd2211e4423c417fc to your computer and use it in GitHub Desktop.
How to convert mouse input to mobile touch in unity
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;
public class HandleMovement : MonoBehaviour {
private Touch myTouch;
private Vector2 mousePos;
private Rigidbody2D rb;
private Vector2 offsetClicked;
private Vector2 offsetReleased;
private void Start()
{
rb = GetComponent<Rigidbody2D>();
offsetReleased = transform.position;
}
void Update()
{
if (Input.touchCount > 0)
{
myTouch = Input.touches[0]; //Get the first touch
mousePos = Camera.main.ScreenToWorldPoint(myTouch.position);
}
}
private void FixedUpdate()
{
// mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
if (Input.touchCount > 0)
{
Vector2 newPos = new Vector2(
Mathf.Clamp(mousePos.x + offsetClicked.x, GameManager.gm.cameraEdges.w + 0.32f, GameManager.gm.cameraEdges.y - 0.32f),
mousePos.y + offsetClicked.y
);
rb.MovePosition(newPos);
offsetReleased = newPos - (Vector2)Camera.main.transform.position;
} //Clicked
else
{
Vector2 newPos = new Vector2(
Mathf.Clamp(Camera.main.transform.position.x + offsetReleased.x, GameManager.gm.cameraEdges.w + 0.32f, GameManager.gm.cameraEdges.y - 0.32f),
Camera.main.transform.position.y + offsetReleased.y
);
rb.MovePosition(newPos);
offsetClicked = newPos - mousePos;
} //Released
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment