- Home /
How to keep an object that was following touch moving in the same diirection on touch release?
I'm making an Android game with a ball that is dropped from the top of the screen. The ball follows the finger (horizontally) until release and then it falls. I want the ball to keep moving in the horizontal direction it was going in if the user is swiping left or right when they release the ball. My attempt at this is shown below but it doesn't work for some reason. Actually, it kind of works in testing but does nothing when I build the app to my phone, which makes me even more confused.
void FixedUpdate () {
if (Input.touchCount > 0 && !dropped) {
else if (Input.GetTouch (0).phase == TouchPhase.Moved) {
// Ball follows finger along top of screen
new_pos.x = mainCamera.ScreenToWorldPoint(new Vector2(Input.GetTouch(0).position.x, spawnHeight)).x;
m_Transform.position = new_pos;
}
else if (Input.GetTouch (0).phase == TouchPhase.Ended) {
// Activate gravity
m_RigidBody2D.constraints = RigidbodyConstraints2D.None;
// Doesn't work
m_RigidBody2D.AddForce(new Vector2(2 * Input.GetTouch (0).deltaPosition.x * Time.deltaTime, 0), ForceMode2D.Impulse);
dropped = true;
}
}
}
There's a lot of material on the problems with moving rigidbody objects from script (setting transform.position) and then using forces - as in don't do that.
There may be techniques where you can turn off rigidbody's reaction to physics until you release it, then turn it back on - I've not used the technique so I'd have to suggest a search on the idea.
That said, do you use physics on the rigidbody after the release, and require it (other than the AddForce in your post)? That may deter$$anonymous$$e how you resolve this issue.
With that said, and it's a caveat you might easily ignore if this is otherwise working for you, consider what deltaPosition does. It gives you the change since the last update. By the time FixedUpdate is subsequently called, deltaPosition should be returning zero (as in you are adding zero force). This could end up being different values in various contexts, meaning you might get a non-zero deltaPosition under certain situations one time, but subsequent FixedUpdates would return a zero, and yet other situations might always return a zero.
Consider tracking the amount of change happening while the touch is moving (in the $$anonymous$$oved phase) using a member variable, which you can then lend to the "Ended" phase as that motion last sense upon release, then stop using delatPosition after an Ended phase has begun.
Your answer
Follow this Question
Related Questions
Applying custom forces without rigidbody collisions? 0 Answers
Throw with mouse 1 Answer
How to move 2D object on touch in Unity 4.3 1 Answer