Page 1 of 1

Complex Collision Detection Doubt

Posted: Thu Jul 24, 2014 9:46 am
by elkiwydev
Hi everyone,
I'm developing a game for quite long now and It's start to get very messy.. Especially with the "beginContact" function..
I want to know if there is any better method to do this :
I have many enemy running around in my level, all the enemy are in "enemyArray[]", and when a enemy touch the wall i want to change his variable of "direction" like this :

Code: Select all

enemyArray[i].direction = -1
But as I did my collision detection, the physic engine only give me the Fixture of the collision, so when an enemy touch the wall I know that someone touched it, but how I can find the index of enemyArray[] of the enemy that touched the wall ?

I did this but it looks pretty rough and not efficent at all:

Code: Select all

if b:getCategory()==11 and a:getCategory()==3 then 
	local x,y  =b:getBody():getLinearVelocity()
	local ind = 0
	for i=1,100 do
		if enemyArray[i] == nil then else 
			if enemyArray[i].fixture ==b then 
				ind = i
			end
		end
	end
	enemyArray[ind].direction = -enemyArray[ind].direction
	if x>0 then b:getBody():setLinearVelocity(-400,0)
	elseif x<0 then b:getBody():setLinearVelocity(400,0)
	end
end 
NB : This code works...I only want to know if there is any better method to do the same thing

Also I still can't figure how to do "If enemyArray != nil then..."
I tryed "!=" ,"not" and "~=" but anything seems to work except doing nothing if is nil and put everything in the "else" part..

Re: Complex Collision Detection Doubt

Posted: Thu Jul 24, 2014 10:13 am
by Plu
You can assign the enemy to the fixture and get recover it from the fixture by using:

Code: Select all

fixture:setUserData( var )
fixture:getUserData()
See: https://love2d.org/wiki/Fixture:setUserData

Re: Complex Collision Detection Doubt

Posted: Thu Jul 24, 2014 12:42 pm
by elkiwydev
Thank you very much, I already tried setUserData a while ago but for some reason it didn't worked..now everything is fine..
Also can I ask you if you know how to do the "not equal" expression?

Re: Complex Collision Detection Doubt

Posted: Thu Jul 24, 2014 3:02 pm
by Plu
You mean to compare if two things are different?

Code: Select all

a ~= b