- Home /
Simultaneously translating and rotating 2D sprite?
I have a 2D object (a PNG file I dragged onto the screen) which is a circle I would like to move left and right when the correct side of the screen is touched and have it rotate in the respective direction while doing so. Naturally, I thought using transform.Translate
and transform.Rotate
would be the proper way to do this, as such:
void Update() {
if (Input.touchCount > 0)
{
var touch = Input.GetTouch (0);
if (touch.position.x < Screen.width/2)
{
transform.Translate (Vector3.left * Time.deltaTime);
transform.Rotate (Vector3.forward * Time.deltaTime);
}
else if (touch.position.x > Screen.width/2)
{
transform.Translate (Vector3.right * Time.deltaTime);
transform.Rotate (Vector3.back * Time.deltaTime);
}
}
}
For whatever reason, rotating left
and right
didn't work so I tried forward
and back
which at least rotated it. The problem is that the circle moves in an arc, I'm assuming because as it rotates, the direction of "right" changes. Also, the circle gets squashed into an ellipse after a bit, assumedly because I'm rotating on the wrong axis. I've literally just started using Unity yesterday; what is the most concise and best way to accomplish what I'd like?
Answer by HEATH3N · Aug 07, 2014 at 11:17 PM
Found the solution courtesy of a user on the GameDev Stack Exchange. The following code works perfectly to achieve what I'd like:
float degreesPerSecond = 45;
if (touch.position.x < Screen.width/2)
{
transform.Translate (Vector3.left * Time.deltaTime, Space.World);
transform.Rotate (Vector3.forward, degreesPerSecond * Time.deltaTime);
}
else if (touch.position.x > Screen.width/2)
{
transform.Translate (Vector3.right * Time.deltaTime, Space.World);
transform.Rotate (Vector3.back, degreesPerSecond * Time.deltaTime);
}