Hi,
I’m new to mobile game development and after following a tutorial on how to make a simple drag/release touch screen script in a 2D project. Basically you drag your finger acroos the phone screen and when you release, force is added to a ball.
I’m wondering what is making this code not work in a 3D project? Here’s the code:
public float power = 10f;
public float maxDrag = 5f;
public Rigidbody2D rb;
public LineRenderer lr;
Vector3 dragStartPos;
Touch touch;
// Update is called once per frame
void Update()
{
if (Input.touchCount > 0)
{
touch = Input.GetTouch(0);
if (touch.phase == TouchPhase.Began)
{
DragStart();
}
if (touch.phase == TouchPhase.Moved)
{
Dragging();
}
if (touch.phase == TouchPhase.Ended)
{
DragRelease();
}
}
}
void DragStart()
{
dragStartPos = Camera.main.ScreenToWorldPoint(touch.position);
dragStartPos.z = 0f;
lr.positionCount = 1;
lr.SetPosition(0, dragStartPos);
}
void Dragging()
{
Vector3 draggingPos = Camera.main.ScreenToWorldPoint(touch.position);
draggingPos.z = 0;
lr.positionCount = 2;
lr.SetPosition(1, draggingPos);
}
void DragRelease()
{
lr.positionCount = 0;
Vector3 dragReleasePos = Camera.main.ScreenToWorldPoint(touch.position);
dragReleasePos.z = 0;
Vector3 force = dragStartPos - dragReleasePos;
Vector3 clampedForce = Vector3.ClampMagnitude(force, maxDrag) * power;
rb.AddForce(clampedForce, ForceMode2D.Impulse);
}
Obviously I’ve changed Rigidbody2D and ForceMode2D to Rigidbody and ForceMode but the line renderer doesn’t start where your finger hits the phone’s screen and there’s no line drag nor force added to the ball. Since it’s Vector3 based, shouldn’t this work in a 3D project?