How to rotate a sprite toward the direction of motion

Hello,

You need the slope of the curve at that point to get the angle.
If you do not have an equation to the curve (for derivative) you will have to use two points on the curve close to your plot point (I used data in an array; an index higher an index lower) to approximate.
See below for example.

I got this to work nicely and animated it as well; the tangent moved across the curve.

This is a Processing (Java) snippet to get you thinking about this:

PVector [] data;

//Slope using atan()
  int x = 200; 
  int off = 10; //smaller the better!
  
  //Slope using atan()
  int i = x;
  float m = (data[i+off].y - data[i-off].y) / (data[i+off].x - data[i-off].x); 
  float angle = atan(m);

  stroke(0);
  strokeWeight(3);
  int i = x;
  line(data[i-off].x, data[i-off].y, data[i+off].x, data[i+off].y); 

To accomplish this at my end:

  1. I created a shape with sine waves (this could have been any data); the shape was built using curveVertex().
  2. I created an array of x, y data for the boundary of shape (stroke(0)) by checking pixel color to see if it was black.
    I had to use noSmooth() otherwise there was blending of colors and I could not get a pure color(0).
  3. Once I have the data for the curve I can use atan() or atan2() to get the angle of the slope of a line at a point on the curve (approximation).
  4. I then translated a line to the point where the tangent is and rotated it with the angle.

It was easier for me to do than explain.

image

Any data version:
frame-000001

:)

4 Likes