I am trying to code in Spigot when a player enchants they get half experience back. So whatever level they are they will get xp to make them half way to the next level.
I tried using player.setExp(50); but that doesn't work and sometimes it creates a second xp bar off to the side and seems glitched.
1 Answer
From the API, emphasis mine:
void setExp(float exp)
Sets the players current experience points towards the next level
This is a percentage value. 0 is "no progress" and 1 is "next level".
Parameters: exp - New experience points
So, if you want to set a player to half a levels experience then use: player.setExp(0.5f);
Edit to address the comment from Kerooker:
Your question is not very clear, but if you want to restore exactly half of the experience used when enchanting, then instead do it like this:
//On the enchantment event use this to find the total cost of the enchant:
int originalCost = event.getExpLevelCost();
//Now update the cost to be half of that and you are all done:
event.setExpLevelCost(int originalCost / 2);
There are many many different ways to do this, for example, you could use int totalEXP = player.getTotalExperience(); before the enchant, then use player.giveExp((totalEXP - player.getTotalExperience()) /2); afterwards to give back exactly half of the experience used. Refer to both API links below.
Source: