- Home /
Topdown Recoil script
Hi! Can someone give me a recoil script that would work on a top down game? I want to make the arm on the robot go back slightly. It is a different sprite.
Answer by karljohnvillardar · Apr 15 at 12:34 PM
Idk if you have figured this out already but I'll leave this here incase anyone is having trouble as well. You just multiply your firepoint direction vector with a matrix of the vector made from an constrained angle you want your bullets to recoil in. Just apply this script to your bullet when firing:
Matrix4x4 recoilMatrix = new Matrix4x4();
Vector4 recoil = new Vector4();
float angle = Mathf.Deg2Rad * Random.Range(-5f,5f); //recoil is 10 degrees total but you can change this
recoil.x = Mathf.Cos(angle);
recoil.y = Mathf.Sin(angle);
recoilMatrix[0, 0] = recoil.x;
recoilMatrix[0, 1] = -recoil.y;
recoilMatrix[1, 0] = recoil.y;
recoilMatrix[1, 1] = recoil.x;
Vector3 direction = recoilMatrix.MultiplyVector(firePoint.up);
rb.AddForce(direction * bulletForce, ForceMode2D.Impulse); //your bullet movement script
Your answer
Follow this Question
Related Questions
Unity2D Space shooter rotation resetting when analogue stick input has ended 1 Answer
How to keep player in bounds? 1 Answer
My raycasting script stops on error in play mode and i can't find out why 1 Answer
How to remove "lines" when using noise setting with cinemachine virtual camera 2 Answers
I need help with a top down 2d shooter 3 Answers