I have a move script that allows the user to touch and move an object around when touch.phase == TouchPhase.Moved. When touch.phase == TouchPhase.Ended, I would like the object to keep moving in the last direction it was going until acted on by a force or gravity pulls it down (not a strong swipe/throw). Also, this is being built with Netcode for GameObjects.
Edit: The issue is that nothing is happening, or it seems as though the AddForce method isn’t doing anything. If gravity is enabled on the rigidbody, it drops immediately after TouchPase.Ended.
public class PlayerController : MonoBehaviour
{
bool moveAllowed = false;
Vector2 startPos, endPos, direction;
private Vector3 offset;
[SerializeField]
float throwForceInXandY = 10f; // to control throw force in X and Y directions
Collider2D col;
Rigidbody2D rb;
// Start is called before the first frame update
void Start()
{
col = GetComponent<Collider2D>();
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void FixedUpdate()
{
Move();
}
public void Move()
{
if (Input.touchCount > 0)
{
Touch touch = Input.GetTouch(0);
Vector2 touchPosition = Camera.main.ScreenToWorldPoint(touch.position);
if (touch.phase == TouchPhase.Began)
{
Collider2D touchedCollider = Physics2D.OverlapPoint(touchPosition);
if (col == touchedCollider)
{
startPos = Input.GetTouch(0).position;
moveAllowed = true;
}
}
if (touch.phase == TouchPhase.Moved)
{
if (moveAllowed)
{
//Move object around screen while touching
transform.position = new Vector2(touchPosition.x, touchPosition.y);
}
}
if (touch.phase == TouchPhase.Ended)
{
moveAllowed = false;
endPos = Input.GetTouch(0).position;
// calculating swipe direction in 2D space
direction = startPos - endPos;
//Object keeps moving in the direction before touch ended
rb.AddForce(new Vector2(direction.x * throwForceInXandY, direction.y * throwForceInXandY));
}
}
}
}