I really need to find a way to create a better throwing mechanic for mobile in unity. For aiming seems to be hard with the current code that I am using atm. I need to find a way to increase power by pulling back (which determines the distance of travel) while aiming left and right, then if I release my finger, then the ball will launch and land on the area that I aimed on.
How do I do this in C# in unity? (Note: I have tried 6 different codes as far as I found in the internet, and the code they wrote is of the same variant as the one I got)
The code that I have wrote so far does the following:
-I press the object, then I can apply power by moving only a little away
from the object to launch powerfully,
or moving my finger far to the edge
of the screen to have the lowest
launch power.
- When I release it, the ball will launch accordingly. Though I must
attest, the mechanic I wrote was only
used for flicking objects, not
necessarily aiming them.
Here’s the pic of the play area and the code that I’m using for the throwing mechanic:
Code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ThrowSimulation2 : MonoBehaviour
{
Vector2 startPos, endPos, dir;
float touchStartT, touchEndT, timeInt;
[SerializeField]
public float touchForceXY = 2f;
[SerializeField]
public float touchForceZ = 50f;
Rigidbody rb;
private void Start()
{
rb = GetComponent<Rigidbody>();
}
private void Update()
{
if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
{
touchStartT = Time.time;
startPos = Input.GetTouch(0).position;
}
if(Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Ended)
{
touchEndT = Time.time;
timeInt = touchEndT - touchStartT;
endPos = Input.GetTouch(0).position;
dir = startPos - endPos;
rb.isKinematic = false;
rb.AddForce(-dir.x * touchForceXY, -dir.y * touchForceXY, touchForceZ / timeInt);
}
}
}
Bump question…