Discord
Login
Community
DARK THEME

How do I create rotational movement?

I'm making a game that needs to be able to make projectiles and enemies move toward any specific direction. Can someone help?

game link: https://microstudio.io/codecat1/bitgrind/3757ZPPG/

its complicated. it goes into trigonometry and stuff like sin cos and tan. ill explain each step one by one but you will probably need to dive deeper yourself.

---------------------------------------------------------------
in order to get the angle use the atan2d function like this.

 atan2d((target x - my x ),( target y - my y))

this returns the angle.
----------------------------------------------------------------
to get the direction to travel you plug them into sin (sin for y) and cos (cos for x) using functions like these.

x += cos(angle)
y += sin(angle)

this should move them 1 in the correct direction.
it only moves them exactly 1 so if you need them to move lets say 5 then multiply them BOTH by 5.
---------------------------------------------------------------

hope that helps

It's perfectly possible to rotate an object without using the sine and cosine functions. The drawing program offers a function called screen.serDrawRotation(angle). Simply create a variable angle and add it to your object. The rotation should then occur. Note that you must set this variable to 0 if you don't want all your sprites to rotate. here is a simple example

init = function()
  angle = 0
end

update = function()
  // Increment the angle
  angle = angle + 2
end

draw = function()
  screen.clear()
  screen.setDrawRotation(angle)
  screen.drawSprite("icon", 0, 0, 50, 50)
  
  // Reset rotation to 0 so it doesn't affect other elements
  screen.setDrawRotation(0)
end

Or you can also use it in the same way that levi_ just explained (it's even very useful in my opinion for tank games)

init = function()

  my_x = 0
  my_y = 0
 
  target_x = 50
  target_y = 50
  angle = 0
  speed = 2
end

update = function()
 
  target_x = mouse.x
  target_y = mouse.y

  angle = atan2d(target_x - my_x, target_y - my_y)

  my_x += cosd(angle) * speed
  my_y += sind(angle) * speed
end

draw = function()
  screen.clear()
  
  // use the calculated angle to rotate the sprite
  screen.setDrawRotation(angle)
  screen.drawSprite("icon", my_x, my_y, 40, 40)
  screen.setDrawRotation(0)
end

don't worry about it being hard. i learned it last year and its still pretty difficult for me. once you learn the basics it gets easier from there.

Thank goodness I'm taking trigonometry classes, it really helps, especially since sine and consine are so useful in fluid and organic motion.

Thanks. I'll try this in the future.

Post a reply

Progress

Status

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