# How to rotate a sprite toward the direction of motion

**URL:** <https://discourse.processing.org/t/how-to-rotate-a-sprite-toward-the-direction-of-motion/21056>\
**Category:** Coding Questions\
**Created:** [May 19, 2020, 2:22pm UTC](https://discourse.processing.org/t/how-to-rotate-a-sprite-toward-the-direction-of-motion/21056 "2020-05-19T14:22:20Z")\
**Posts on this page:** 1\
**Showing post:** 12

<div class="post-metadata">

**Author:** ![glv](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/glv/32/18785_2.png) [@glv](https://discourse.processing.org/u/glv)\
**Post date:** [May 19, 2020, 8:52pm UTC](https://discourse.processing.org/t/how-to-rotate-a-sprite-toward-the-direction-of-motion/21056/12 "2020-05-19T20:52:12Z")

</div>

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:

```auto
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](https://canada1.discourse-cdn.com/flex036/uploads/processingfoundation1/original/2X/6/654c27427de0c2904d91c27054f8f7b51f19baa2.png)

_Any data_ version:  
 ![frame-000001](https://canada1.discourse-cdn.com/flex036/uploads/processingfoundation1/original/2X/e/e957311cae05b8380fedee9d561d11c695b68eda.gif)

`:)`

---

_[View the full topic](https://discourse.processing.org/t/how-to-rotate-a-sprite-toward-the-direction-of-motion/21056)._
