- Home /
Move an object in 2D space along the angle of the object
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;
Answer by robertbu · Nov 25, 2013 at 07:22 PM
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.
Holy cow I did not know it was that simple! Thanks a lot!
Your answer
Follow this Question
Related Questions
Move Object With Angle In 2D 1 Answer
A node in a childnode? 1 Answer
2D : Rotation of Object With x-y Axis 2 Answers
How to alternate images in 2d unity 0 Answers
2D scene level design Help 2 Answers