RigidBody2D detect Collision from the side

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Leoseverini
:warning: Old Version Published before Godot 3 was released.

Hi.
In a game, I have a world made of boxes (StaticBody2D) and some objects that the main character can move, I made it of RigidBody2D because also can be dropped to the floor from a higher lever.
The Main character is a RigidBody2D too.
I made an animation for pushing the objects.
How can I detect the objects from that I pushing (from the sides)?
Here is the code of the movement of the character

Input.is_action_pressed("ui_left"):
   set_axis_velocity(Vector2(-mov_velocity,0))	

So I want to run the animation when this actions is happend and is colliding from the side.

Thanks

:bust_in_silhouette: Reply From: avencherus

I wasn’t clear if you were driving RigidBodies with animation nodes, but if not, generally you could do something like this with code inside the RigidBody in question.

extends RigidBody2D   

func _ready():
	set_max_contacts_reported(4)

func do_stuff():
	pass #Do my stuff here

func _integrate_forces(state):

	var width = 30
	var left_side = get_pos().x - width

	var contacts = state.get_contact_count()
	
	if(contacts > 0):
		for i in range(contacts):
			if(left_side <= state.get_contact_collider_pos(i).x):
				do_stuff()
				break

You can do this in fixed process too if don’t want to use a custom integrator and change contacts reported (and monitoring) on the inspector

eons | 2016-10-17 23:08

Hi
Thanks for you answer.
This didn’t work for me, because I have others collisions on the floor with the same type of block, so I cant check the type too.
But it helps me a lot to find a solution.
All the blocks are in a Matrix with position index. So I made a function that translate the position of the object on the position of the matrix, and when I get a collision and I make a movement to the sides, I check the position on the matrix and I know if is on the side or is on the bottom of the character
Here is the final function if someone need it.

func _integrate_forces(state):	
var contacts = state.get_contact_count()
if(contacts > 0):
	for i in range(contacts):
		var obj = state.get_contact_collider_object(i)
		if obj != null:
			if obj.has_method("getMatrixPos"):
				var objPos = obj.getMatrixPos()
				var characterPos = getMatrixPos()
				var dif = objPos - characterPos
				
				if (dif.y == 0) and hdir != 0:
					anim = "pushing"
				else:
					anim = "idle"
					hdir = 0

hdir is -1 if the the left input is pressed and 1 if the right is pressed. 0 If none.

Thanks

Leoseverini | 2016-10-18 06:49

You’re quite welcome, glad you were able to find a solution it for your setup. X)

avencherus | 2016-10-18 08:41