id is not transmitted through event

Summary
local function collision_champ (self, event)
	local phase = event.phase;
	**local id = event.target.id**
	
	if (phase == "began") then
		print( event.other.identy );
		print( id );
		
		if ( id == "champ" and event.other.identy== "drop") then
			print("HEro")
		else
			print("not HEro")
		end
	end
	return true
end

for i,t in pairs(decoded) do
	t.name = display.newImage(sceneGroup, "img/local/champs/musketeer/musketeer.png", _W/math.random(1,8), _H/math.random(1,8));
	t.name:scale( champ_view+minScale, champ_view+maxScale );
	t.id = t.id;
	t.name.collision = collision_champ;
	t.name:addEventListener( "collision" );
	t.name:addEventListener( "touch", drag_champ );
end

decoded is json:
{
“1p”:
{
“name”:“champ_shoot”,
“id”:“champ”
},
“2p”:
{
“name”:“champ_vampir”,
“id”:“champ”
},
“3p”:
{
“name”:“champ_fish”,
“id”:“champ”
},
}

why in the console?:
03:13:50.469 drop
03:13:50.469 nil
03:13:50.469 not HEro

how I can get id “champ”?

Which platform are you developing on PC or Mac and for Android or iOS?

Can you please explain your question more clearly?

First of all, I suggest you create new objects and properties instead of changing the existing properties of t. For example in the code below, changing t.name from a string value to a display object is not good practice if you want your code to be clean and readable. Create a new table to hold your display objects instead.

for i,t in pairs(decoded) do
	t.name = display.newImage(sceneGroup, "img/local/champs/musketeer/musketeer.png", _W/math.random(1,8), _H/math.random(1,8));
	t.name:scale( champ_view+minScale, champ_view+maxScale );
	t.id = t.id;
	t.name.collision = collision_champ;
	t.name:addEventListener( "collision" );
	t.name:addEventListener( "touch", drag_champ );
end

To answer your original question about why id is nil in the listener. It’s because you add the event listener to t.name, and t.name does not have an id property.

The quickest way to solve the problem is by changing the following line:

t.id = t.id; -- (This is btw a completely unnecessary assignment)

to

t.name.id = t.id;

Haven’t test run your code, but I’m quite sure that will work.

1 Like

Thanks for the answer! Works :slight_smile:

From the beginning I want to understand the mechanics in order to plan the development of the game further on the android platform. I have no experience in creating games, so now I try everything through my mistakes and spend a lot of my time on the page https://docs.coronalabs.com/api/index.html

Be encouraged! Corona (now Solar2D) is, IMHO, the best 2D engine anywhere!

1 Like