1
\$\begingroup\$

I am working on a 2D topdown game where you have cars you can drag around. you can touch any given car and move it around. This kind of works but when I drag a curve the sprit of the car does not turn in direction of its movement but rather moves sideways.

I need a way to rotate the sprite towards input (touch,mouse) and be updated as long as the input "is down" but I am unsure how to calculate and update the angle each frame.

I do not want to use velocity towards the input but rather drag and drop while "clicking" on the sprite.

enter image description here

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

When you hold the mouse button down, begin tracking the location of the mouse.

Every frame, compare the current location with the location on the previous frame.

If the vector from previous to current is large enough, orient the car in the direction of the vector.

When you release the mouse button, stop: tracking, comparing and rotating.

EDIT

private bool PerformRotation = false;
private Vector2D LastFramePosition

OnMouseButtonClicked()
{
    PerformRotation = true; 
    LastFramePosition = Car.Position;
}

OnMouseButtonReleased()
{
    performRotation = false;
}

Tick()
{
    if(performRotation)
    {
        Vector2D CurrentMouseLocation = Mouse.getLocation();
        Vector2D LastFrameToCurrent = CurrentMouseLocation - LastFramePosition;

        Car.ForwardVector = LastFrameToCurrent.Normalize();

        LastFramePosition = CurrentMouseLocation;
    }
}

\$\endgroup\$
2
  • \$\begingroup\$ is the position of the mouse sufficient for this calculation or do i need the position of the car itself as well? Could you give an example on how you would compare /store the frame location? \$\endgroup\$
    – KonMos
    Mar 23, 2020 at 14:44
  • \$\begingroup\$ @KonMos I have edited my answer to include a pseudocode solution \$\endgroup\$
    – Natalo77
    Mar 23, 2020 at 15:41

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .