- Home /
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:
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.
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);
}
}
Answer by Sazails · Oct 15, 2019 at 06:07 PM
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. Have fun finding this information, it really helps you to develop skills in a fun way.
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;
}
}
}
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.
Just wanted to say thanks for your kind reply, but somehow im still struggling(yeah, im not a genius myself lol)
Answer by oguzkagan · May 17, 2020 at 12:13 PM
i found the solution in this video: https://youtu.be/RoZG5RARGF0
Answer by Batuhan13 · May 17, 2020 at 12:58 PM
Hi mate could you check this link pls =) ? Stackoverflow link
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.
Your answer
Follow this Question
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