Discord
Login
Community
DARK THEME

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
 update = function()
    //make the circle follow the mouse
    local posX = round(mouse.x)
    local posY = round(mouse.y)
    
    //calculating the angle (only if the circle is moving)
    if not (preX == posX and preY == posY) then
      angle = atan2d(posY - preY, posX - preX)
    //updating the previous coordinates
      preX = round(x)
      preY = round(y)
      x += cosd( angle ) 
      y += sind( angle )
    end
  end

Well I wanted the circle to always be where the cursor is... but you made me realize that the only problem in my code is that the cursor changes the angle quickly due to proximity, so your code is better!
I made some changes though:

distance = function(x1, y1, x2, y2)
  local dx = x2 - x1
  local dy = y2 - y1
  return sqrt(pow(dx, 2) + pow(dy, 2))
end
  
update = function()
  //make the circle follow the mouse
  local posX = round(mouse.x)
  local posY = round(mouse.y)
    
    
  if distance(x, y, posX, posY) > 5 then
    //calculating the angle (only if the circle is moving)
    if not (preX == posX and preY == posY) then
      angle = atan2d(posY - preY, posX - preX)
        
      //updating the previous coordinates
      preX = round(x)
      preY = round(y)
        
      //speed based on distance between mouse and the circle
      local speed = distance(x, y, posX, posY)/5
        
      x += cosd(angle) * speed
      y += sind(angle) * speed
    end
  end
end

Post a reply

Progress

Status

Preview
Cancel
Post
Validate your e-mail address to participate in the community