How to make objects 'fall' towards each other?

Assuming you’re not using dynamic collision objects, you can do something like this (untested!):

-- Tweak this to suit your game
local GRAVITY = 10

function init(self)
	self.velocity = vmath.vector3()
end

function update(self, dt)
	local current_position = go.get_position()
	
	-- Get the unit vector (vector of length 1) representing the direction from the player to the planet
	local direction = vmath.normalize(go.get_position("planet") - current_position)
	
        -- Apply gravity to the vector to get acceleration in the proper direction
        -- Then add this acceleration vector to our current velocity
	self.velocity = self.velocity + (direction * GRAVITY)

        -- Now all we have to do is add our velocity to our current position to get our next position
	go.set_position(current_position + (self.velocity * dt))
end
5 Likes