Enemy attacking player

Hi,
i got the script so when the enemy and player collide the player loses 1 health however whenever i walk past the enemy, my health goes down so fast , i was wondering if there is a fix

local function player_damage(self)
	self.player_health = self.player_health - 1
	if self.player_health <=0 then
		game_over(self)
	print("OUCH! player damage == ",self.player_health)
end

This happens so fast

There’s an issue with your formatting - it’s missing an ‘end’ for your if statement. Try this instead:

local function player_damage(self)
	self.player_health = self.player_health - 1

	if self.player_health <=0 then
		game_over(self)
	end

	print("OUCH! player damage == ",self.player_health)
end
1 Like

Thanks for letting me know however it didnt fix the issue that the enemy attacks really fast which means that my player character would be dead in a instant

Okay. The problem is elsewhere than the snippet of code you posted.

It’s hard to imagine your function producing the given output as you are subtracting 1 from health but it appears to be subtracting 10.

okay

This is the collision detection for the enemy script

function on_message(self, message_id, message, sender)
	if message_id == hash("contact_point_response") then
		msg.post("/hero#heromove", "simple_damage")
	end
end


and simple damage is just a hash

local msg_simple_damage=hash("simple_damage")

That looks all right. It appears as though something else is diminishing the player health variable.

We need to see the whole project really, if you can zip it up and post here.

do you think its something to do with my collision objects?

As Ben mentioned, you’re subtracting 1, but the printout shows you’ve subtracted 10.

I’m guessing you’re getting multiple collision responses, and issue a player damage event for each one.

Check that the player is part of the collision, by checking the values in the message:

pprint(message_id, message) -- will print the contents of the message

i changed it so that the damage is 1

my problem is that it attacks really fast

contact_point_response is sent for each contact point, and for each frame, so you need to use some mechanic to make sure you only register the collision once.

You could e.g. use a trigger instead to detect if they touch.

3 Likes

That worked after a bit thanks