Page 1 of 1

Rectangle Collision Function Help

Posted: Mon Apr 29, 2013 10:04 pm
by darkroom
Hello so I am making a game where you eat smaller fish to grow larger to eat bigger fish and so I need a way for the player to collide with fish. I tried to make myself a collision function but it doesn't work. Can someone show me a rectangle collision function?
My collision function:

Code: Select all

function player:collidiesWith(other)
	if not other.rect then
		other.rect = makeRect(other)
	end
	local lMost, rMost, bMost, tMost
	if self.rect.left < other.rect.left then
		lMost = self.rect
		rMost = other.rect
	else 
		lMost = other.rect
		rMost = self.rect
	end
	if self.rect.top < other.rect.top then
		tMost = self.rect
		bMost = other.rect
	else
		tMost = other.rect
		bMost = self.rect
	end
	local xdist = rMost.left - lMost.right
	local ydist = bMost.top - tMost.bottom
	return xdist <= 0 and ydist <= 0
end
My full program code is below

Re: Rectangle Collision Function Help

Posted: Tue Apr 30, 2013 3:18 am
by vitaminx
Hi,

I've written a rectangular collision detection for your game and added the width/height of player and fishes to their tables to make calculation easier.

Here's the collision part:

Code: Select all

function player:collidiesWith(other)
    if other.x+other.width>self.x and other.x<self.x+self.width and other.y+other.height>self.y and other.y<self.y+self.height then return true
    else return false end
end
Other changes are in entities:spawn(), entities:load(), entities:checkCollision() and player:load().
Use diff to find them ^^

Another hint: you use a similar table.insert in both entities:spawn() and entities:load(). You should avoid any duplication of code, maybe make a function for the insert?

Greets,
vitaminx

Re: Rectangle Collision Function Help

Posted: Tue Apr 30, 2013 4:28 am
by spynaz
Hey I just finished a game like that......well similar. XD
You can check out the code. It has circle and rectangle collision detection functions.

http://love2d.org/forums/viewtopic.php?f=5&t=33349

Re: Rectangle Collision Function Help

Posted: Fri May 03, 2013 7:30 pm
by Puzzlem00n
I remember a time, long ago when I came on here often, when people would always link this for questions like these, and thus I shall do the same. :D

P.S @Vitaminx: Helping people doesn't always mean doing all their work for them. It's better to stop, guide them through it, and explain.