Touch object and apply vertical force

Hello,

I have a game object, and i want to “touch it” or “click it” and apply vertical force to move it.

Which is the best way to do that?

Thanks

I’m not sure how far along in your experiment you’ve gotten but these are the steps you need to take:

  1. Create a game object with a collision object of type dynamic
  2. Add a script to either the game object itself or some controller game object
  3. Let the script acquire_input_focus
  4. Add an input binding for MOUSE_BUTTON_1. This will let you receive both mouse clicks and touch actionshttp://www.defold.com/manuals/input/#_mouse_triggers.
  5. In the on_input() function of the script you can read the mouse/touch position and post an apply_force message to the point where the user clicked/touched.

Something like this assuming that the script is attached to the game object with the collision object. If it’s not, then you need to change the url when posting the apply_force:

function init(self)
	msg.post(".", "acquire_input_focus")
end

function on_input(self, action_id, action)
	-- hash("touch") must correspond to the action you specified in your input bindings
	if action_id == hash("touch") and action.released then
		-- the force must be sufficiently large
		-- you might want to get the mass of the collision object and take that into account
		msg.post(".", "apply_force", { force = 100000, position = vmath.vector3(action.x, action.y, 0) })
	end
end

Note that this example doesn’t take into account if the object was touched or not. If you want to only allow a force to be applied when the object was touched you also need to detect if the click/touch happened on the collision object in question or not. Check this example for a way to use collision objects to detect this.

2 Likes