Hi there!
I’m having issues getting my bullet prefab to ricochet off a wall. I’ve already got a successful bouncing enemy that uses similar code, but because these enemies aren’t controlled by user interaction - and head off in a set direction - they work (bounce) perfectly. It’s another issue entirely for bullets fired by the player, however.
The issue - based on the code below - results in my bullets either firing correctly in correct direction but not bouncing upon hitting wall, OR bouncing correctly, but with the bullet ONLY firing forwards. Aiming elsewhere does nothing.
Here is the code that’s on my bullet prefab:
transform.position += transform.forward * speed * Time.deltaTime;
Ray ray = new Ray(transform.position, transform.forward);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, Time.deltaTime * speed + .1f,collisionMask))
{
Vector3 reflectDir = Vector3.Reflect(ray.direction, hit.normal);
float rot = 90 - Mathf.Atan2(reflectDir.z, reflectDir.x) * Mathf.Rad2Deg;
transform.eulerAngles = new Vector3(0,rot,0);
}
And here is the relevant code from my PlayerShooting script:
if(Time.time >= coolDown && GameObject.Find ("Obelisk_Base_SE").GetComponent<ObeliskCommandSE> ().isActivated == false)
{
if(Input.GetMouseButton(0))
{
NoShootAnkhAward = 20f;
FireBounce();
GetComponent<AudioSource> ().Play ();
numberOfBullets ++;
}
}
void FireBounce()
{
Rigidbody bPrefab = Instantiate(bulletPrefab,transform.position, Quaternion.identity) as Rigidbody;
bPrefab.GetComponent<Rigidbody>().AddForce(transform.up * bulletSpeed);
coolDown = Time.time + attackSpeed;
}
From what I can tell, the issue seems to be a conflict between bPrefab.GetComponent().AddForce(transform.up * bulletSpeed); from my PlayerShooting script, and transform.position += transform.forward * speed * Time.deltaTime; from my ricochet code.
Any help would be super appreciated - I’m pretty new to Unity/C# and have got myself pretty confused over this one.
Many thanks!