I wanted bullets to bounce when they hit walls. However when colliding with a wall, they just jitter about on them. I didn't want to create a new physics material as I want to keep the ball moving at a constant speed and to have them destroy themselves after they have bounced once. Thus, I wrote everything in Code.
The constraints for the bullet rigidbody's freezing position is the Y axis while the freezing rotation is X, Y, and Z axis.
I also wondered if the initial position the instantiated bullet also had something to do with the speed the bullet travels:
GameObject bulletObject = Instantiate(bulletPrefab);
bulletObject.transform.position = transform.position + (transform.forward * -1);
Here's the minimum reproducible code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class bulletMovement : MonoBehaviour
{
private Rigidbody bulletRB;
private Vector3 lastVelocity, initialVelocity;
public float bulletSpeed = 10f;
private int bounceCount;
// Start is called before the first frame update
private void Start()
{
bulletRB = GetComponent<Rigidbody>();
bounceCount = 0;
bulletRB.AddForce((transform.forward* -1) * bulletSpeed);
}
void Update()
{
lastVelocity = bulletRB.velocity;
}
// Update is called once per frame
private void OnCollisionEnter(Collision col)
{
if (col.collider.tag == "Walls")
{
bounceCount += 1;
if (bounceCount < 2)
{
Bounce(col.contacts[0].normal);
}
else
{
Destroy(gameObject);
}
}
}
private void Bounce(Vector3 normal)
{
var speed = lastVelocity.magnitude;
var direction = Vector3.Reflect(lastVelocity.normalized, normal);
Debug.Log("Out Direction: " + direction);
bulletRB.velocity = direction * Mathf.Max(speed, bulletSpeed);
}
}
lastVelocity = bulletRB.velocity; is required to be in Update or else the bullet won't move at all.