How to make objects 'fall' towards each other?

Hi I’m new with using defold and I’ve been messing around with the physics in the game, however it seems like there is not much control over the direction of gravity. I’ve been trying to make it so objects will fall towards one centre object, much like they would when falling down. Eg: if I were to spawn an object to the side, or below this centre object it would ‘fall’ sideways or upwards towards it. Is there any possible way to do this simply, I’m not very experienced so any help would be appreciated.

1 Like

There is no way to set the gravity for individual game objects, so I think your best option is to use apply_force every frame, to make each game object move towards the target game object in the middle.

3 Likes

@totebo is correct. There is no way to set gravity at runtime (yet). And even if it did, it would be applied to all objects. (Physics engines usually treat the gravity as a global force that is applied each frame)

As suggested, you are better off calculating this yourself.
Set the gravity to 0, and calculate a force to be applied for each object in the update function.

4 Likes

I’m not sure you understand, I want objects to fall towards the target object no matter the targets position or the spawned in objects position, as if it where a planet.

Hmm, just thinking out loud, but isn’t such effect possible with joints?

1 Like

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

This seemed to work with a bit of tweaking, Thank you!

One little tweak to that: You should also multiply GRAVITY by dt in update so the acceleration isn’t different for different framerates.

3 Likes