[SOLVED] 2D Collision issue

Defold client: 1.6.4
I have a basic implementation of a cat moving from left to right. It changes directions when it detects wall collision. This works great when the wall is taller than the actual cat object. However when the wall is shorter than the cat collision box (see image) the cat does not change direction (there are cases when it decides to change direction after walking into the wall for some amount of time but its rare).

Does anyone know why this could be happening?

image

Cant you share the code for dealing with the collisions? Hard to say otherwise.

This is what currently have

local function handle_obstacle_contact(self, normal, distance, other_id)
if distance > 0 then
    local proj = vmath.project(self.correction, normal * distance)
    if proj < 1 then
        -- Only care for projections that does not overshoot.
        local comp = (distance - distance * proj) * normal
        -- Apply compensation
        go.set_position(go.get_position() + comp)
        -- Accumulate correction done
        self.correction = self.correction + comp
    else
        -- collided with a wall; change direction
        if math.abs(normal.x) > .7 then
            self.facing_direction = self.facing_direction * -1 
        end
    end
end

-- collided with the ground. stop vertical movement
if normal.y > 0.7 then
    self.ground_contact = true
    self.velocity.y = 0
end
end

function on_message(self, message_id, message, sender)
	if message_id == msg_contact_point_response then
		-- check that the object is something we consider an obstacle
		if message.group == group_obstacle then
			handle_obstacle_contact(self, message.normal, message.distance, message.other_id)
		end
	end
end

Hmm, the code looks okay. It might be that you’re receiving multiple collision messages in a single frame which results in the code switching directions twice, thus continuing in the same direction. You could put a print statement after self.facing_direction = self.facing_direction * -1 to check this.

4 Likes

Forgot to get back to this… This solution fixed my issue!