I’m making a brick breaker game, and I’m trying to detect which side of the bricks the ball is hitting, so I can know which way to make the ball bounce.
I have this script attached to each of the bricks, and I’m trying to use raycasting to figure out which side of the brick the ball hits. It works part of the time, but sometimes the ball goes right through the object. Does anyone know how I can fix this?
using UnityEngine;
using System.Collections;
public class Brick : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
void OnCollisionEnter(Collision collision) {
// Raycasting to determine what side of the brick the ball hits
Ray myRay = new Ray(transform.position, collision.gameObject.transform.position);
RaycastHit myRayHit;
Physics.Raycast(myRay, out myRayHit);
Vector3 myNormal = myRayHit.normal;
myNormal = myRayHit.transform.TransformDirection(myNormal);
if (myNormal == gameObject.transform.forward) {
// If the ball hits the top of the brick
Destroy(gameObject);
collision.gameObject.GetComponent<Ball>().speedZ = -collision.gameObject.GetComponent<Ball>().speedZ;
}
else if (myNormal == -gameObject.transform.forward) {
// If the ball hits the bottom of the brick
Destroy(gameObject);
collision.gameObject.GetComponent<Ball>().speedZ = -collision.gameObject.GetComponent<Ball>().speedZ;
}
else if (myNormal == gameObject.transform.right) {
// If the ball hits the right of the brick
Destroy(gameObject);
collision.gameObject.GetComponent<Ball>().speedX = -collision.gameObject.GetComponent<Ball>().speedX;
}
else if (myNormal == -gameObject.transform.right) {
// If the ball hits the left of the brick
Destroy(gameObject);
collision.gameObject.GetComponent<Ball>().speedX = -collision.gameObject.GetComponent<Ball>().speedX;
}
}
}