Why button pressed increases speed?

Hey everybody!

I’m building my endless run game in Corona Sdk. I’m using Composer and Widget libraries to create scenes and buttons.

The problem:
I have my player walking and two buttons for jumping and crouching. I can’t understand why when the buttons are pressed, the scrolling speed of background and ground increases and my enemies start “scrolling” the other way. This leads to a Corona Simulator Runtime error when player and enemy collide, instead of game over scene.

Actually I need speed to increase but haven’t write the code yet :sweat_smile:

This is the scrolling function:
local function scroller (self, event)
local speed = speedIncrement
if self.x < -(display.contentWidth-speed2) then
self.x = 2
display.contentWidth-speed*2
else
self.x = self.x-speed
end
end

This is the buttons code
local function ButtonPressed(event)
local target = event.target
local targetId = target.id
if event.phase ==“ended” then

		if targetId =="1" then
			if not player.isJumping then
					print ("Salta")
					player.isJumping=true
			
					player:applyLinearImpulse(0,-15,player.x,player.y)
					player:setSequence("jump")
					player:play()
					player:addEventListener( "sprite", walkAgain )

end

		elseif targetId =="2" then
			if not player.isCrouching then
					print ("Abbassati")
					player.isCrouching=true
					player:setSequence("crouch")
					player:play()
					player:addEventListener( "sprite", walkAgain )
			end
		end
		player.isNotWalking = true	
	end

end

I don’t use the physics engine(very often - hardly ever) so I am very un-sure about physics code … but does the ‘applylinearimpulse’ called each button press somehow accumulates the impulse amount? But you likely know more about the physics then I do. Either way I would look at that first - but I am guessing on that.
But without seeing all the code, another thing to look at at least, is the event listener adding to player object each button press. Unless you are removing the eventListener each time before button is pressed again, that could be causing some issues as well. This is a guess without see more of your code. Ideally (again without seeing more of the code) I would assign that event listener ‘once’ somewhere when you create ‘player’ object.

I hope this helps in some way.

1 Like

Thanks!! It was the eventListener! I used a tap event to start the game so everytime I tapped the function run!

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