# Calculating the angle of an object's direction based on its motion

I want to calculate the angle of an object's direction that is following the mouse, i did that by storing the previous coordinates (`preX`

, `preY`

) and then calculate the angle with this formula: `angle = atan2d(y - preY, x - preX)`

. This works almost as expected but not completely. (I also want to calculate the angle only if the object is moving, if the object is not moving than the angle must maintain his previous value)

```
circle = object
init = function()
x = mouse.x //x of the circle
y = mouse.x //y of the circle
preX = mouse.x //previous x
preY = mouse.y //previous y
angle = 0
end
update = function()
//make the circle follow the mouse
x = mouse.x
y = mouse.y
//calculating the angle (only if the circle is moving)
if not (preX == x and preY == y) then
angle = atan2d(y - preY, x - preX)
end
//updating the previous coordinates
preX = x
preY = y
end
draw = function()
screen.drawRound(x, y, 20, 20, "#FFF")
//draw the line to show the angle
screen.drawLine(x, y, x + cosd(angle)*20, y + sind(angle)*20, "red")
end
end
```