Discord
Login
Community
DARK THEME

A Point Towards Function?

I want to make a point towards a position function.I tried and it didn't work.Do you know a way?

Hi there :)

How to calculate it, or how to rotate the object towards the position?

The formula to calculate the angle between 2 points with known x/y coordinates is:

angle = atan2( y2-y1, x2-x1 )

So you need to keep track of the x/y of your item, best done by defining it as an object, OR by using @gilles Quickengine :)

To draw the rotated object you have to use the screen.setDrawRotation() function as shown below.

DO NOT FORGET TO SET IT BACK TO ZERO ... hahaha, I speak from experience

arrow = object
  angle = 0
  x     = 0
  y     = 0
  
  draw = function()
    screen.setDrawRotation(angle)
    screen.drawSprite("arrow",x,y,40)
    screen.setDrawRotation(0)
  end
end

// calculates the angle between 2 points
point2 = function(x1,y1,x2,y2)
  return atan2d(y2-y1,x2-x1)
end  

And then you can use it like this:

init = function()
end

update = function()
  arrow.angle = point2(arrow.x,arrow.y,mouse.x,mouse.y)
end

draw = function()
  screen.clear()
  arrow.draw()
end 

:embed https://microstudio.io/TinkerSmith/point/WAJ4XC8M/

Clumsy example done on phone, could be better (as in, same as the object has its own draw routine you could define it as custom update).

Otherwise, if I misunderstood the question just clarify :)


Live Long And Tinker

P.S. using Quickengine a quick and dirty way could look like this:

init = function()
  Quick.init()
  Quick.gravity  = 0
  arrow = Quick.addSprite("arrow")

  // add our 'custom' function to the arrow object
  arrow.point2 = function(obj)
      arrow.rotation = atan2d(obj.y-y,obj.x-x)
  end

end

update = function()
  arrow.point2(mouse)  // or any other object with x/y coordinates
end

draw = function()
  Quick.draw()
end

Live Long And Tinker

It seems to break when the mouse is outside the test space/play space.

As said, it was a 'quick & dirty' example to show the general idea.
If the target is the mouse it is advisable to check and limit to a minimum/maximum range :)


Live Long And Tinker

Post a reply

Progress

Status

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