I'm trying to create a Pong clone for practice. I setup my project in 2D.
The paddle has the following components:
- -Rigidbody2D (set to
kinematic
) - -BoxCollider2D (is a
trigger
)
The ball has the following components:
- -Rigidbody2D (set to
kinematic
) - -CircleCollider2D (is a
trigger
)
The paddle is controlled via dragging (user dragging finger on screen left/right). I used the EasyTouch
plugin for this.
Then I move the ball with this script:
void Update () {
transform.position += new Vector3(xSpeed * Time.deltaTime, ySpeed * Time.deltaTime);
}
This is how I detect collisions and redirect the ball once it hits something (Horizontal objects are the top/bottom/paddle while Vertical objects are the left/right screen border):
void OnTriggerEnter2D(Collider2D c)
{
if(c.gameObject.tag.Equals("Horizontal"))
{
ySpeed *= -1;
}
else if(c.gameObject.tag.Equals("Vertical"))
{
xSpeed *= -1;
}
}
The problem is sometimes the ball goes through the paddle which can look glitchy to the end-user. I've searched about this online and I've tried to set the rigidbody's Collision Detection
property to Continuous
instead of Discrete
. But the ball still goes through the paddle at certain times.
Anyone know how to solve this? What am I doing wrong with how I setup/coded my game?
Thanks