I am currently making a 2D slingshot game and would like to have it work on mobile devices. Currently my code has it working with OnMouseDown() but i’m not sure how to substitute it for touch controls, so it would really help if somebody can inform me how to get it working.
Here is my current script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Ball : MonoBehaviour
{
private bool isPressed;
private float releaseDelay;
private float maxDragDistance = 3f;
//ball components
private Rigidbody2D rb;
private SpringJoint2D sj;
private Rigidbody2D slingRb;
private LineRenderer lr;
public BoxCollider2D ground;
//on startup, get the rigidbody of the ball
private void Awake()
{
rb = GetComponent<Rigidbody2D>();
sj = GetComponent<SpringJoint2D>();
lr = GetComponent<LineRenderer>();
slingRb = sj.connectedBody;
lr.enabled = false;
releaseDelay = 1 / (sj.frequency * 4);
}
// Update is called once per frame
void Update()
{
if (isPressed)
{
DragBall();
}
}
private void DragBall()
{
SetLineRendererPositions();
//places the ball wherever the mouse is positioned, henced "drag"
//only works when the mouse is directly touching the ball but might change this
Vector2 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
float distance = Vector2.Distance(mousePosition, slingRb.position);
if(distance > maxDragDistance)
{
Vector2 direction = (mousePosition - slingRb.position).normalized;
rb.position = slingRb.position + direction * maxDragDistance;
} else
{
rb.position = mousePosition;
}
}
private void SetLineRendererPositions()
{
Vector3[] positions = new Vector3[2];
positions[0] = rb.position;
positions[1] = slingRb.position;
lr.SetPositions(positions);
}
//mouse press actions
private void OnMouseDown()
{
isPressed = true;
//changes the rigidbody from dynamic to kinematic
//lets the pull force not counteract the spring force
rb.isKinematic = true;
lr.enabled = true;
}
private void OnMouseUp()
{
isPressed = false;
//changes the rigidbody from kinematic to dynamic
rb.isKinematic = false;
//triggers the Release() method
StartCoroutine(Release());
lr.enabled = false;
}
private IEnumerator Release()
{
yield return new WaitForSeconds(releaseDelay);
sj.enabled = false;
ground.enabled = true;
}
}