Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 14 Next capture
2021 2022 2023
2 captures
12 Jun 22 - 14 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
1
Question by unity_4ErgdcF4dqxeIA · Oct 15, 2019 at 05:26 PM · 2dprojectilereflectionbounce

Unity 2D-¿How do I make a bullet bounce off the wall?

Hi, this problem has been anoying me for weeks, since i just found solutions for this but with 3D, or using raycast, and since i want the bullet to bounce of the wall and make the player able to react i was a little loss(as far as i know raycast doesnt allow this, but im a nooby in programming and unity so i could be wrong). Ideal Bounce: alt text

Here is my Script for the bullet:

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 public class Bullet : MonoBehaviour
 {
     public GameObject hitEffect1;
     public GameObject hitEffect2;
 
     void OnCollisionEnter2D(Collision2D collision)
     {
         GameObject effect = Instantiate(hitEffect1, transform.position, Quaternion.identity);
         Destroy(effect, 0.3f);
         Destroy(gameObject);
         //Accediendo a la variable del Script "Weapon", para que se añada una municion al contador cada vez que explota una bala.
         GameObject TanqueVerde = GameObject.Find("TanqueVerde");
         Weapon BulletScript = TanqueVerde.GetComponent<Weapon>();
         BulletScript.Munición += 1;
 
         if (collision.gameObject.name == "Enemigo01")
         {
             Destroy(gameObject);
             //Eliminando el efecto de impacto 1 que solo debe funcionar con las paredes, asi solo se ve el efecto de destrucción del enemigo"
             Destroy(effect, 0.0f);
 
         }
        if (collision.gameObject.name == "Pared")
         {
            
 
         }
         
 
 
     }
 
    
 }

And just in case here is my script that is attached to the player:

 using UnityEngine;
 public class Weapon : MonoBehaviour
 {
     public Transform FirePoint;
     public GameObject BalaPrefab;
     public float bulletSpeed = 20f;
     //Haciendo una condicion para poder disparar
     public bool canShoot = true;
     public int Munición = 3;
 
     void Update()
     {
         if (Input.GetButtonDown("Fire1"))
         {
             if (canShoot == true)
             {
                 Shoot();
                 Munición -= 1;
             }
                 
         }
         
         if (Munición >=1)
         {
             canShoot = true;
         }
 
         if (Munición <= 0)
         {
            canShoot = false;
         }
     }
     void Shoot()
     {
        GameObject bullet = Instantiate(BalaPrefab, FirePoint.position, FirePoint.rotation);
         Rigidbody2D rb = bullet.GetComponent<Rigidbody2D>();
         rb.AddForce(FirePoint.up * bulletSpeed, ForceMode2D.Impulse);
     }

Any help would be apreciated, thanks.

bullet.png (167.2 kB)
Comment
Add comment · Show 1
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image BVGuled · Jun 05, 2021 at 08:51 AM 0
Share

please check the below code, apply it to bullet which should have rigidbody with gravity 0 and a circle collider 2d

  public float speed;
 
     private void Update()
     {
         transform.Translate(Vector2.up * Time.deltaTime * speed);
     }
 
     private void OnCollisionEnter2D(Collision2D collision)
     {
         if(collision.gameObject.tag == "wall")
         {
             ContactPoint2D point = collision.contacts[0];
             Vector2 newDir = Vector2.zero;
             Vector2 curDire = this.transform.TransformDirection(Vector2.up);
 
             newDir = Vector2.Reflect(curDire, point.normal);
             transform.rotation = Quaternion.FromToRotation(Vector2.up, newDir);
         }
     }

7 Replies

· Add your reply
  • Sort: 
avatar image
2

Answer by Sazails · Oct 15, 2019 at 06:07 PM

  1. Get the collision surface normal up.

  2. Get the angle hit compared to the normal up in angles.

  3. Set bullet rotation towards the angle direction.

  4. Add force to the bullet forward with the force at the impact if needed. Have fun finding this information, it really helps you to develop skills in a fun way.

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image unity_4ErgdcF4dqxeIA · Oct 27, 2019 at 11:00 PM 0
Share

Thanks a lot for your reply it helped me to have a direction, its been almost 2 weeks and im still triying to do this thing lmao, would you $$anonymous$$d helping me one more time? i just could get the bullet to have a good ricochet but the bullet doesnt rotates towards its new angle, if you feel like helping me again, here is my code(eli$$anonymous$$ated all the innecesary things so is easier to read):

public class Bullet : $$anonymous$$onoBehaviour { public Rigidbody2D rb; public float BulletSpeed = 20f; Bullet gunBullet;

 void Start()
     {
         rb.velocity = transform.up * BulletSpeed;
         gunBullet = GetComponent<Bullet>();
     }
 void OnCollisionEnter2D(Collision2D collision)
     {
         if (collision.gameObject.CompareTag("Pared"))
         {
             Vector2 reflectedPosition = Vector3.Reflect(transform.up, collision.contacts[0].normal);
             rb.velocity = (reflectedPosition).normalized * gunBullet.BulletSpeed;
             Vector2 dir = rb.velocity;
             float angle = $$anonymous$$athf.Atan2(dir.y, dir.x) * $$anonymous$$athf.Rad2Deg;
             rb.$$anonymous$$oveRotation(angle);
             rb.angularVelocity = 0;
 
         }
 }
 }

avatar image
1

Answer by anszwa · Oct 15, 2019 at 05:59 PM

One simple way to do this would be to let the physics engine do it for you. Just create a Physics Material (Asset - Create - Physics Material2D, set the bounce value of it to 1, the friction to 0 and attach it to the collider of the bullet. For recalculating the rotation of the bullet, some LookAt function in Collision Enter should do the job.

.

The other way would be to simulate the bounce via script. You will have to get the face normal by raycast and then use some vector math (like Vector2.Reflect) to calculate the exit angle, which you will need to get the new direction of the bullet. But for prototyping, I would recommend you to first try out the physical way.

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image unity_4ErgdcF4dqxeIA · Oct 27, 2019 at 11:11 PM 0
Share

Just wanted to say thanks for your kind reply, but somehow im still struggling(yeah, im not a genius myself lol)

avatar image
0

Answer by oguzkagan · May 17, 2020 at 12:13 PM

i found the solution in this video: https://youtu.be/RoZG5RARGF0

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
0

Answer by Batuhan13 · May 17, 2020 at 12:58 PM

Hi mate could you check this link pls =) ? Stackoverflow link

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
0

Answer by Dawsns · May 18, 2020 at 08:47 AM

Get the collision surface normal up. Get the angle hit compared to the normal up in angles. Set bullet rotation towards the angle direction. Add force to the bullet forward with the force at the impact if needed.

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
  • 1
  • 2
  • ›

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

232 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

(2D) Face Object in Direction of Travel 1 Answer

Bounce when hitting wall 2 Answers

How do i make something reflect in 2D? 1 Answer

ball breaks through walls 1 Answer

How to make two objects collide without bouncing 2D 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges