Hello,
I was wondering how I could convert this script into using touch controls on Android or IOS.
Would it be as easy as just replacing Input.getMouseButttonDown or Input.mousePosition with GetTouch?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DragObject : MonoBehaviour
{
[SerializeField] float moveSpeed;
[SerializeField] float saveDelay = 0.2f;
float power = 5f;
Rigidbody2D rb;
Vector2 dir;
Vector2 lastPosition;
DestroyObject inAir;
bool nextSave = true;
bool canBePushed;
private bool following;
// Use this for initialization
void Start()
{
following = false;
lastPosition = transform.position;
rb = GetComponent<Rigidbody2D>();
inAir = FindObjectOfType<DestroyObject>();
}
// Update is called once per frame
void Update()
{
MouseClicksToDrag();
}
//drags objects
private void MouseClicksToDrag()
//detects if object has mouse clicked on it
{
if (Input.GetMouseButtonDown(0))
{
RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector3.forward);
if (hit.collider != null && hit.collider.gameObject == this.gameObject)
{
following = true;
}
}
// detects if object has been released to add forces
if (Input.GetMouseButtonUp(0) && following)
{
following = false;
dir = (Vector2)transform.position - lastPosition;
canBePushed = true;
}
if (following)
{
transform.position = Vector2.Lerp(transform.position, Camera.main.ScreenToWorldPoint(Input.mousePosition), moveSpeed);
}
if (nextSave)
{
StartCoroutine("SavePosition");
}
}
void FixedUpdate()
{
IfCanBePushed();
}
private void IfCanBePushed()
{
{
if (!inAir.IsFallingTrue())
{
if (canBePushed)
{
canBePushed = false;
rb.velocity = dir * power;
}
}
}
}
IEnumerator SavePosition()
{
nextSave = false;
lastPosition = transform.position;
yield return new WaitForSeconds(saveDelay);
nextSave = true;
}
}