- Home /
Raycasting to detect which side of collider is hit
Hi all, I have a problem i can't solve (since i'm not experienced in Raycasting that much). Imagine a cannon on the ground shooting up in the air trying to hit a cube (game object which has box collider). I'm trying to detect on collision with the projectile which side of the cube was hit, any help is appreciated.
void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.tag.Equals("my_cube"))
{
var hit = HitDirection();
Debug.Log(hit);
}
}
bool IsRightOrLeftHit()
{
RaycastHit hit;
Ray rayUp = new Ray(transform.position, Vector3.up);
Ray rayDown = new Ray(transform.position, Vector3.down);
Physics.Raycast(rayUp, out hit);
Physics.Raycast(rayDown, out hit);
return hit;
}
This script is attached to my "cannon ball" object btw.
Answer by text23d · Nov 30, 2017 at 08:07 PM
I used dice asset (see on asset store), it used some logic to know which side is up. maybe here is similar?
Answer by Buckslice · Nov 30, 2017 at 08:22 PM
Maybe something like this will work?
void OnCollisionEnter(Collision collision) {
if (collision.gameObject.CompareTag("my_cube")) {
Vector3 n = collision.contacts[0].normal;
Transform t = collision.collider.transform;
if (n == t.right) {
Debug.Log("hit right side");
}else if (n == -t.right) {
Debug.Log("hit left side");
} else if (n == t.up) {
Debug.Log("hit top side");
} else if (n == -t.up) {
Debug.Log("hit bottom side");
} else if (n == t.forward) {
Debug.Log("hit front side");
} else if (n == -t.forward) {
Debug.Log("hit back side");
}
}
}
Your answer
Follow this Question
Related Questions
Raycast not Detecting Colliders 2 Answers
Fall collision force with help of raycast 0 Answers
Detect RaycastHit on Character Controller 2 Answers
Need Help with RayCast. No Vector? 1 Answer
Raycast Not Drawing In Target Direction 0 Answers