2D physics, can anyone explain why this happens?

I am attempting to make 2D physics for circles atm but they act weird, instead of bouncing away they get pulled to another.

local function circleIntersect(x1, y1, r1, x2, y2, r2)
	-- Calculate the distance between the two circles
	local squareDistance = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2);
	
	-- When the distance is smaller or equal to the sum
	-- of the two radius, the circles touch or overlap
	return squareDistance <= ((r1 + r2) * (r1 + r2))
end

local function detectCollision()
	local obj1
	local obj2

	for index, object in gameObjects do
		object.isColliding = false
	end
	
	for index = 1, #gameObjects do
		obj1 = gameObjects[index]
		
		for newIndex = index + 1, #gameObjects do
			obj2 = gameObjects[newIndex]
			
			if obj1.shape == obj2.shape then
				if obj1.shape == 'Square' then
					if rectIntersect(obj1.x, obj1.y, obj1.w, obj1.h, obj2.x, obj2.y, obj2.w, obj2.h) then
						obj1.isColliding = true;
						obj2.isColliding = true;
					end
				else
					if circleIntersect(obj1.x, obj1.y, obj1.r, obj2.x, obj2.y, obj2.r) then
						obj1.isColliding = true;
						obj2.isColliding = true;
						
						local vCollision = Vector2.new(obj2.x - obj1.x, obj2.y - obj1.y);
						local distance = math.sqrt((obj2.x - obj1.x) * (obj2.x - obj1.x) + (obj2.y - obj1.y) * (obj2.y - obj1.y));
						local vCollisionNorm = Vector2.new(vCollision.x / distance, vCollision.y / distance);
						
						local vRelativeVelocity = Vector2.new(obj1.vx - obj2.vx, obj1.vy - obj2.vy);
						local speed = vRelativeVelocity.x * vCollisionNorm.x + vRelativeVelocity.y * vCollisionNorm.y;
						
						if (speed < 0) then
							break
						end
						
						obj1.vx -= (speed * vCollisionNorm.x);
						obj1.vy -= (speed * vCollisionNorm.y);
						obj2.vx += (speed * vCollisionNorm.x);
						obj2.vy += (speed * vCollisionNorm.y);
					end
				end
			end
		end
	end
end

I have no idea what causes this.

1 Like

Fixed it, it was a misplaced vector.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.