Gravity

How do we set the gravity centre for the physics engine?
For example, how do we make everything be pulled towards the centre of the screen? Do we have to just apply a force to everything?

You have to apply a force to everything, there is no gravity centre

I did a bunch of posts on creating your own physics engine, including objects with gravity, starting here

https://coolcodea.wordpress.com/2013/10/16/124-vectors-and-physics-an-introduction/

This first post refers to a fantastic ebook that covers the programming of forces like gravity really well

@Ignatz Oh, ok. I’m fine with physics: you were the one who told me to use the in built engine actually. XD

Not with planetary gravity, though

I think the underlying Box2D engine supports orbital gravity though. I’ve been playing with it in SpriteKit (which is also Box2D-backed). So it might be something to request as a feature for Codea.

Here’s a simple example of gravity at the center of the screen.You have to turn off box2d gravity and calculate your own gravity. There’s other ways, but this seemed the easiest. A lot of the values were tweaked to get this to work.

displayMode(FULLSCREEN)

function setup()
    tab={}
    -- create objects affected by gravity
    for z=1,10 do
        local s=physics.body(CIRCLE,5)
        s.x=WIDTH/2+5*z
        s.y=HEIGHT/2+45*z
        s.gravityScale=0     -- turn off box 2d Gravity.
        s:applyForce(vec2(50-4*z,0))
        table.insert(tab,s)
    end   
    -- create the center gravity position.
    s1=physics.body(CIRCLE,5)
    s1.x=WIDTH/2
    s1.y=HEIGHT/2
    s1.type=STATIC   -- keep the gravity at the center.
    s1g=6000   -- amount of gravity 
end

function draw()
    background(40,40,50)
    fill(255)   
    ellipse(s1.x,s1.y,20)
    for a,b in pairs(tab) do
        d=s1g/((b.x-s1.x)^2+(b.y-s1.y)^2)^1.5  -- calculate your own gravity
        dx=(s1.x-b.x)*d*4
        dy=(s1.y-b.y)*d*4
        b:applyForce(vec2(dx,dy))
        ellipse(b.x,b.y,15)
    end
end

@dave1707 a few things.

  1. Wouldn’t it be easier to use vectors, especially with the inbuilt vector functions?
  2. Where did you account for the masses of the two objects/ did you?
  3. Why do you multiply by 4 on the dx and dy?
    Thanks for your help.

@MattthewLXXIII I just hacked this from one of my other projects. I’m sure things could be improved on this. I’m not accounting for masses directly, but s1g could be a mass value. The higher the value, the more gravity there is. As for other variables, things were tweaked just to get it to look good. This code only accounts for gravity of the center object and ignores any gravity of the other objects. My other code calculates gravity for each object and how they interact.