Discord
Login
Community
DARK THEME

how to make a sprite point in the direction of the mouse?

I am making a shooter game where the gun points in the direction of the mouse pointer. But I don't know how to do so. Can anyone help me?

mouseDrag = function() 
  if mouse.right and mouse.press then 
    oldXOffset=oldMouseX 
    oldYOffset=oldMouseY
    print(mouse.x) 
    print(oldXOffset) 
  end
  if mouse.release then 
    if ((mouse.x != oldMouseX) and 
       (mouse.y != oldMouseY)) then 
        xOffset=oldMouseX - mouse.x
        yOffset=oldMouseY - mouse.y
        oldMouseX=mouse.x 
        oldMouseY=mouse.y 
    end
  end 
end
init = function()
  oldMouseX=mouse.x 
  oldMouseY=mouse.y
  oldXOffset=mouse.x
  oldYOffset=mouse.y 
  xOffset=mouse.x
  yOffset=mouse.y
  img = sprites[ 'icon' ]
  img.x = 0
  img.y = 0
end

update = function()
  mouseDrag()
  img.x = ( img.x *99 + mouse.x ) / 100
  img.y = ( img.y *99 + mouse.y ) / 100 
  print( img.x)
end

draw = function()
  screen.clear()
  screen.drawSprite( img.name, img.x, img.y, img.width, img.height )
  screen.setColor("rgb(255,255,255)")
  
  screen.drawRound( mouse.x, mouse.y, 10, 10 )
  screen.drawText( "mouse( x= " + floor(mouse.x) + ", y= " + floor(mouse.y) + ")", mouse.x, mouse.y-15, 15 )
  screen.drawRound( oldMouseX, oldMouseY, 10, 10 )
  screen.drawText( "oldMouse( x= " + floor(oldMouseX) + ", y= " + floor(oldMouseY) + ")", oldMouseX, oldMouseY-15, 15 )

  screen.drawRound( 0, 0 , 10, 10 )
  screen.drawText( "center", 0, -10, 15)
  screen.drawLine( mouse.x, mouse.y, oldMouseX, oldMouseY )

  screen.drawText( "xOffset= " + floor(xOffset) , -150, 80, 15 )
  screen.drawText( "yOffset= " + floor(yOffset) , -150, 60, 15 )

end

thanks, but what does this code do?

It always pays to check out the Examples section, here is one for rotating sprites:

https://microstudio.dev/i/JimB007/turnsprite/

Simplified, you use the x/y coordinates of the mouse and the object to calculate the angle. Then you rotate the object accordingly.

Thank You

Post a reply

Progress

Status

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