- Home /
ricochet bounce effect issue
First of all im really new to unity and programming, soo expect a loot of noob mistakes :)
Hi , im trying to make a 2D game where the bullet bounces off the walls like a ricochet . I got to the point where i can shoot it to the direction im pointing with the ,, gun '' the way i wanted it , then i attached a RAY to it, pointing towards direction its going to . Now im stuck at the bounce effect , i trying to use the Vector3.reflect but its not bouncing the way i would expect it to bounce .It bounces off almost randomly and sometimes its going though the box colliders . I created a 3d box colliders in the places where the walls are , because i found out that rays don't detect 2d colliders or something like that? . I would like to know if the mistake is in my code or the scene design . I will appreciate every help,tip and criticism :) thanks
This is the code
void Update () {
Vector3 fwd = transform.TransformDirection(Vector3.up);
//Debug.DrawRay(raycastObject.transform.position, fwd * raySize, Color.green);
RaycastHit hit;
Ray ray = new Ray (transform.position , fwd * raySize ) ;
Debug.DrawRay (transform.position, fwd * raySize);
if (Physics.Raycast (ray , out hit, raySize )) {
Debug.Log ("Bouce test 1 ");
if (hit.collider.tag == "Wall") {
Debug.Log ("Bounce test 2 ");
Vector3 reflectDir = Vector3.Reflect (ray.direction , hit.normal);
float rot = Mathf.Atan2 (reflectDir.y, reflectDir.x) * Mathf.Rad2Deg;
transform.eulerAngles = new Vector3 (0, 0, rot);
}
Also this is the bit im using for movement of the bullet
Vector3 pos = transform.position;
Vector3 velocity = new Vector3 (0, speed * Time.deltaTime, 0);
pos += transform.rotation * velocity;
transform.position = pos;
Answer by Tabemasu Games · Jan 27, 2015 at 07:19 PM
If I were you, I'd give the direction (fwd) to the bullet
transform.position += fwd * speed * Time.deltaTime;
Then, you just have to change this direction when bouncing:
myBullet.fwd = Vector3.Reflect (ray.direction , hit.normal);
If you want the bullet to have a rotation which depends on this direction, simply do:
transform.rotation = Quaternion.LookRotation(fwd);
Hi , sorry i didnt reply , i changed some things in the scene , i made the camera look from the top down and it all works perfect :)
Your answer
![](https://koobas.hobune.stream/wayback/20220613181649im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Flat 2D bounce against gravity? 2 Answers
Enemy bounce from screen edges 0 Answers
Unity 2D Ball Stuck on wall when bouncing 2 Answers
Multiple Cars not working 1 Answer
Cast multiple rays from an object between two angles? 0 Answers