- Home /
How do I give my 2D ball a real ball behavior?
I'm new to programming and trying to figure out how do make a 2D ball feel like a ball.
What is the problem im having?
When I drag my finger on the phone to add velocity to the ball its works fine, the problem im having is the ball keeps moving and never stopps, it glides slowly to a diration after colliding with a wall.
I added 2D physics material to Rigidbody 2D with friction .5 and bounce .1
What do i want?
I want the ball after colliding with anything to slowly lose its speed to complete zero. Just like a real ball would do. I cant figure it out.
What have i tried doing?
I have tried adding Rigidbody drag Timer Physics.sleepAngularVelocity
rb drag did work but it was to sudden stop.
public class BollControll : MonoBehaviour { public float power = 10f; public float maxDrag = 5f; public Rigidbody2D rb; public LineRenderer lr; Vector3 dragStartPos; Touch touch;
private 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);
dragStartPos.z = 0f;
lr.positionCount = 2;
lr.SetPosition(1, draggingPos);
rb.isKinematic = false;
}
void DragRelease()
{
lr.positionCount = 0;
Vector3 dragReleasePos = Camera.main.ScreenToWorldPoint(touch.position);
dragReleasePos.z = 0f;
Vector3 force = dragStartPos - dragReleasePos;
Vector3 clampedForce = Vector3.ClampMagnitude(force, maxDrag) * power;
rb.AddForce(clampedForce, ForceMode2D.Impulse);
}
}