I’ve seen this question before raised many times, but I have not gotten a satisfactory answer that has actually worked for me. I’m trying to get a cannon to have a little recoil animation: it moves to a position just behind where it previously was, and slides back. I also want to have this cannon on an angle. So, what I’m trying to do is simply move it backwards along its angle.
I’m working in 2D so this should be fairly simple, but for some reason this is not working out.
This is my code so far, which I got from another article but isn’t working for me:
int speed = 1;
float angle = transform.rotation.eulerAngles.z * Mathf.Deg2Rad;
Vector2 newTransform = new Vector2(Mathf.Sin(angle) * speed, Mathf.Cos(angle) * speed);
transform.position = newTransform;
`
`
Since you are checking the rotation around the ‘z’ axis, I assume your gun is either pointed along the object’s ‘right’ or the object’s ‘up’. Assuming ‘right’, then you can do this for your recoil:
transform.position = transform.position - transform.right * factor;
…where ‘factor’ is the distance you want it to move.