2D Sprite: Rotation/translation issue

Hi,

So this is long, but I’m trying to be detailed.

I’m instantiating a sprite, setting a target position (based on a mouse click and collision detection), then each Update() I move the sprite toward that target at a fixed speed. When I do this without any form of rotation, it works perfectly. However, when I add the following rotation code in, everything goes crazy.

Vector3 rotationOrigin = player.position;
Vector3 rotationTarget = targetPoint;

Vector3 rotationDirection = (rotationTarget - rotationOrigin);
float rotation = Vector3.Angle(Vector3.right, rotationDirection);

if (rotationTarget.y < rotationOrigin.y)
    rotation *= -1;

Vector3 eulerRotation = new Vector3(0.0f, 0.0f, rotation);
Quaternion quatRotation = Quaternion.Euler(eulerRotation);

I know there’s some extra variables and such in there, but I’m started breaking every piece down when things weren’t working as intended. My goal is to make the sprite rotate to face the direction it’s traveling in, then continue to travel toward the target. It rotates, but the traveling to the target part is weird. Here’s the code to translate it:

if (Vector3.Distance(transform.position, target) > (TRAVEL_SPEED * Time.deltaTime))
{
    direction = (target - transform.position).normalized;
    myTransform.Translate(direction * TRAVEL_SPEED * Time.deltaTime);
}
else
{
    myTransform.position = target;
}

There’s some extra logic to switch to a different delegate in the else statement, but I don’t believe it’s relevant here. Now, with the above 2 combinations, there’s a sort of offset that occurs, the sprite rotates, but the movement is all off. If it’s traveling almost horizontal to the X axis, then the offset isn’t noticeable. However, the greater the angle of rotation, the bigger the offset is in the direction you’re rotating from.

To try and explain this better, I’ve included a visual (it happens too fast in game for me to grap a real screenshot, and I warn you, I am no artist).

30971-example.jpg

If it’s traveling along the green line, the sprite rotates properly and you can barely tell there’s an offset issue. When traveling along the blue line, the sprite still rotates correctly, but gets offset further back down. The reverse is true if the blue line has a negative Y vector and is traveling down, but the sprite ends up having a higher y value (position) then it should.

I really appreciate anyone who actually takes the time to read this, and I’d greatly appreciate any assistance or pointing me in the right direction (pun not intended).

Thank you,

Shawn

In second piece of code direction vector calculated in world coordinate space, but Translate function in your code applied in sprite’s local coordinate space, which is rotated relative to world and it gives offset from wanted trajectory. So you need to add second parameter to Translate:

myTransform.Translate(direction * TRAVEL_SPEED * Time.deltaTime, Space.World);