- Home /
Problems with Box Collider 2D
Hi, I did do a pong game , but when i do a speciffic action , the ball get out of the box (the box is the limit) , and i don't know what is happening . this is the code of the raquets , and the ball . I need to do something with Box Collider , where can i found the problem of this "bug" , thanks
Raquets
using UnityEngine;
using System.Collections;
public class MoveRacket : MonoBehaviour {
public float speed = 30;
public string axis = "Vertical";
void FixedUpdate () {
float v = Input.GetAxisRaw(axis);
GetComponent<Rigidbody2D>().velocity = new Vector2(0, v)* speed;
}
}
the ball
using UnityEngine;
using System.Collections;
public class Ball : MonoBehaviour
{
public float speed = 30;
void Start ()
{
// Initial Velocity
GetComponent<Rigidbody2D> ().velocity = Vector2.right * speed;
}
void OnCollisionEnter2D (Collision2D col)
{
if (col.gameObject.name == "RacketLeft") {
// Calculate hit Factor
float y = hitFactor (transform.position,
col.transform.position,
col.collider.bounds.size.y);
Vector2 dir = new Vector2 (1, y).normalized;
GetComponent<Rigidbody2D> ().velocity = dir * speed;
}
if (col.gameObject.name == "RacketRight") {
float y = hitFactor (transform.position,
col.transform.position,
col.collider.bounds.size.y);
Vector2 dir = new Vector2 (-1, y).normalized;
GetComponent<Rigidbody2D> ().velocity = dir * speed;
}
}
float hitFactor (Vector2 ballPos, Vector2 racketPos,
float racketHeight)
{
return (ballPos.y - racketPos.y) / racketHeight;
}
}
Answer by lordlycastle · Apr 24, 2015 at 01:48 PM
It’s not a bug, the problem is that the rigidbody of the side, and the ball is small so it passes through the sides. You can make the rigid bodies a little larger, or you can change the collision detection method of the ball’s rigidbody to Continuous Dynamic. You can read about the different collision detection method here and make a decision as to use which type for what.
Your answer
![](https://koobas.hobune.stream/wayback/20220613193912im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
unity 3d pong improve AI 0 Answers
Box Collider Position Problem 0 Answers
Cant get Collisions to work 3 Answers
Issues with jump control for player 1 Answer
KeyCode to Ui ? for mobile 1 Answer