I am working on a game like soccer star and I made a controller using YouTube and stuff. I added two players in the same scene and put this script on them. But when I play with player 1, then player 2 does the same as they are controlled by the same touch. How can I make them work simultaneously?
The Upper half belongs to player 1 and the lower half belongs to player 2 and they are touching the same screen.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Ball : MonoBehaviour
{
public float Power = 10f;
public float maxDrag = 5f;
Rigidbody2D rb;
LineRenderer lr;
Vector3 dragStartPos;
Touch touch2;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
lr = GetComponent<LineRenderer>();
}
// Update is called once per frame
void Update()
{
if (Input.touchCount > 0)
{
touch2 = Input.GetTouch(0);
if (touch2.phase == TouchPhase.Began)
{
dragStart();
}
if (touch2.phase == TouchPhase.Moved)
{
dragging();
}
if (touch2.phase == TouchPhase.Ended)
{
dragRelease();
}
}
}
void dragStart()
{
dragStartPos = Camera.main.ScreenToWorldPoint(touch2.position);
dragStartPos.z = 0f;
lr.positionCount = 1;
lr.SetPosition(0, transform.position);
}
void dragging()
{
Vector3 draggingPos = Camera.main.ScreenToWorldPoint(touch2.position);
draggingPos.z = 0f;
lr.positionCount = 2;
lr.SetPosition(0, draggingPos);
}
void dragRelease()
{
lr.positionCount = 0;
Vector3 dragReleasePos = Camera.main.ScreenToWorldPoint(touch2.position);
dragReleasePos.z = 0f;
Vector3 force = dragStartPos - dragReleasePos;
Vector3 clampedForce = Vector3.ClampMagnitude(force, maxDrag) * Power;
rb.AddForce(clampedForce, ForceMode2D.Impulse);
}
}