I have a Square and a circle. With the crank you can rotate the square around the circle. With the arrows you can move the circle.
But when you move the circle in some direction, the Square is also moving. I do not get why it is doing this. I have to admit I am not great at math. But my understanding was that in the update loop the x and y values of the circle will be gotten from that current position. If the circle is moved - the square should just rotate relative to that position and not move along with it.
Anyone has any idea what I am overlooking or doing wrong?
Below is the full code from main.lua:
import "CoreLibs/object"
import "CoreLibs/graphics"
import "CoreLibs/sprites"
local pd <const> = playdate
local gfx <const> = pd.graphics
local circle = nil
local square = nil
local function init()
-- Square
local fillRect = gfx.image.new(100, 100)
square = gfx.sprite.new(fillRect)
gfx.pushContext(fillRect)
gfx.fillRect(0, 0, 100, 100)
gfx.popContext()
square:setImage(fillRect)
square:moveTo(200, 50)
square:add()
-- Circle
local r = 10
local circleImage = gfx.image.new(r * 2, r * 2)
circle = gfx.sprite.new(circleImage)
gfx.pushContext(circleImage)
gfx.fillCircleAtPoint(r, r, r)
gfx.popContext()
circle:setCollideRect(0, 0, r * 2, r * 2)
circle:setImage(circleImage)
circle:moveTo(200, 120)
circle:add()
end
init()
function pd.update()
local angle = pd.getCrankPosition()
-- ROTATION of square around circle
local a = square.x - circle.x
local b = square.y - circle.y
local r = math.sqrt( a * a + b * b )
local x = circle.x + r * math.cos( math.rad(angle) )
local y = circle.y + r * math.sin( math.rad(angle) )
square:moveTo(x, y)
square:setRotation(angle)
-- Circle move
if pd.buttonIsPressed('up') then
circle:moveBy(0,-2)
end
if pd.buttonIsPressed('right') then
circle:moveBy(2,0)
end
if pd.buttonIsPressed('down') then
circle:moveBy(0,2)
end
if pd.buttonIsPressed('left') then
circle:moveBy(-2,0)
end
gfx.sprite.update()
end