Question by
Alistar3000 · Aug 27, 2018 at 05:16 AM ·
touch controlsthrowing
Problem throwing GameObject on Z axis with AddForce
I'm pretty new to Unity and C# but struggling along ok. I'm a bit stuck with a script to throw a GameObject along the X axis. I can throw the object, but only along the X and Y axes - the Z axis stays the same.
The script I'm using is:
Vector3 startPos, endPos, direction;
float touchTimeStart, touchTimeFinish, timeInterval;
private Rigidbody rb;
public float throwSpeed = 30f;
void Start() {
rb = GetComponent<RigidBody>();
}
void Update() {
// if you touch the screen
if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
{
// getting touch position and marking time when you touch the screen
touchTimeStart = Time.time;
startPos = Input.GetTouch(0).position;
}
// if you release your finger
if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Ended)
{
// marking time when you release it
touchTimeFinish = Time.time;
// calculate swipe time interval
timeInterval = touchTimeFinish - touchTimeStart;
// getting release finger position
endPos = Input.GetTouch(0).position;
// calculating swipe direction in 2D space
direction = endPos - startPos;
// add force to cat rigidbody in 3D space depending on swipe time, direction and throw forces
rb.isKinematic = false;
rb.useGravity = false;
catLatch.transform.DetachChildren();
rb.AddForce((direction * throwSpeed / 20.0f) + Vector3.forward * throwSpeed);
}
}
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220612173544im_/https://answers.unity.com/themes/thub/images/avi.jpg)