Hello,
I am attempting to build a top-down shooter where the bullets will ricochet off the walls for infinity. I am having real difficulty getting my bullets to stop going through my colliders. I have done every Google search and tried different things:
- My walls are done using a Tilemap. I have tried the tilemap collider which didn’t work. I then removed that and added box colliders to the walls.
- I have added rigidbody 2D components to the wall colliders above and my bullet also has a circle collider 2D and rigidbody 2D. The Collision Detection for both the rigidbodies is set to Continuous.
- I had a go at changing the Project Settings > Time > Fixed Timestep which actually worked, but had a negative impact on my player rotation, so I had to remove it.
- I have read every thread I could find and watched countless YouTube videos on raycasts. Unfortunately, the majority of these are for 3D and as much as I try to manipulate the code examples, they either give errors or don’t seem to do anything at all.
I am really struggling with this. It seems like raycasts might be the solution, but I have no idea how to implement it and can’t find a suitable 2D tutorial about it.
Here is the code I have now, which is letting bullets through the walls, like water through a sieve!
The Player_Shooting script is attached to the player object
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player_Shooting : MonoBehaviour
{
[SerializeField] private Transform _firePoint;
[SerializeField] private GameObject _bulletPrefab;
[SerializeField] private float _bulletForce;
private void Update() {
if (Input.GetButtonDown("Fire1")) {
Shoot();
}
}
private void Shoot() {
GameObject bullet = Instantiate(_bulletPrefab, _firePoint.position, _firePoint.rotation);
Rigidbody2D rb = bullet.GetComponent<Rigidbody2D>();
rb.AddForce(_firePoint.right * _bulletForce, ForceMode2D.Impulse);
}
}
The Bullet_Bounce script is attached to the instantiated bullet:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Bullet_Bounce : MonoBehaviour {
[SerializeField] private Rigidbody2D _rb;
private Vector3 _lastVelocity;
private void Update() {
_lastVelocity = _rb.velocity;
}
private void OnCollisionEnter2D(Collision2D other) {
var speed = _lastVelocity.magnitude;
var direction = Vector3.Reflect(_lastVelocity.normalized, other.contacts[0].normal);
_rb.velocity = direction * Mathf.Max(speed, 0f);
}
}
If anyone could assist me with this, I would really appreciate it.
Many Thanks,
J