Search code examples
graphics2dcoordinatesd2d-games

Align shape to vector using Dgame framework and D language


I've been using Dgame framework for simple simulations.

I need moving object to be aligned to their velocity vectors.

How is it possible to do that using Dgame?

I see that shape object has setRotation and setRotationCenter. Not sure how to use these to achieve the effect. I realize that default is rotation around origin. This causes objects to drift over time.

Sample code

struct GameObject {
Point **position;
// array of pointers to object points
Point *acceleration;
Point *velocity;
double max_speed;
double max_force;
}

shape = new Shape(Geometry.Quads,
Vertex(object.position[0].x, object.position[0].y),
Vertex(object.position[1].x, object.position[1].y),
Vertex(object.position[2].x, object.position[2].y),
Vertex(object.position[3].x, object.position[3].y))

// rotate shape to face velocity here
shape.move(object.velocity.x, object.velocity.y);

Solution

  • You can achieve this using atan2. Depending on the orientation of the texture you might need to change the values a bit or add 90/-90 degrees.

    For textures that face up:

    rotation = atan2(-velocity.x, velocity.y);
    

    For textures that face right:

    rotation = atan2(-velocity.y, -velocity.x);
    

    You might need to convert the result from radians to degrees or the other way around.