#help-development
1 messages · Page 2166 of 1
wait someone mentioned about base64
I'll look into it, thanks
try it out?
Ah ok.
im sorry :c
im sorry :(
not u
I've got a small problem with the Vector#rotateAroundY Method. I rotate the vector around y with that method by 360°/amount of locations. When I have 3 as the amount it spawns them right next to each other instead of spreading them around the location passed in.
Am I not understanding the rotateAroundY() method correctly?
The method takes radians
radians yeah
so instead of passing it the degrees I would pass in Math.toRadians(degrees)
u can use Math.toRadians to convert
oh ok
thats fair
is 2pi a circle?
ye
1 rad is pi
ohh
wait no
in radians, yes
1 pi is a half circle
1 radian is not pi
radians remember me on VALORANT
And to check if it's with the if ? ```java
NamespacedKey key = new NamespacedKey(plugin, "shop-key");
ItemStack chestGUI = new ItemStack(Material.CHEST, 1);
ItemMeta meta_chestGUI = chestGUI.getItemMeta();
meta_chestGUI.getPersistentDataContainer().set(key, PersistentDataType.DOUBLE, Math.PI);
meta_chestGUI.setDisplayName("Shop");
chestGUI.setItemMeta(meta_chestGUI);
PersistentDataContainer container_chestGUI = meta_chestGUI.getPersistentDataContainer();
if (container_chestGUI.has(key, PersistentDataType.DOUBLE)) {
double foundValue = container_chestGUI.get(key, PersistentDataType.DOUBLE);
}
pi radians is 180 degrees
Hello, how can I remove collisions between players and mobs? setCollidable() doesn't work and I tried with this:
scoreboard = Bukkit.getScoreboardManager().getNewScoreboard();
afk = scoreboard.registerNewTeam("afk");
afk.setOption(Team.Option.COLLISION_RULE, Team.OptionStatus.NEVER);
is the player in the team?
yes Main.getInstance().afk.addPlayer(p);
the Math.toRadians() works perfectly, thank you 😄
Correct
No need to use a double though, just a byte is enough
less space
But waht is the goal of "foundValue" ?
You want the main scoreboard. Not a new one
You don;t need to read the value, you just need to see if the entry exists
Alr.
Don't name your class Main and don't have public fields like that
If it exists then its your custom item
why ? i can't call my variable if i do that
quick question: Is someone using the Threads function?
it's the same
getters protect your fields. You can alter teh code behind a getter however you like, but the end point is always the getter
Correct? ```java
NamespacedKey key = new NamespacedKey(plugin, "shop-key");
ItemMeta meta = item.getItemMeta();
PersistentDataContainer container_chestGUI = meta.getPersistentDataContainer();
if (container_chestGUI.has(key, PersistentDataType.DOUBLE)) {
InteractShop(plr, action, item);
}
ew this space
apply the meta back to the item. meta is a clone
This part of the code is in a function.
when you are setting the PDC flag, you need to put the meta back on the item after
getItemMeta() fetches you a clone of the meta that is on the item. Use setMeta to put the meta back after altering it
Okay so I'm trying to make a harvester hoe and I'm running into a tiny issue here.
@EventHandler
void breakCrop(BlockBreakEvent e) {
Block block = e.getBlock();
Player p = e.getPlayer();
Location loc = block.getLocation();
loc.setY(loc.getY() + 1);
Block blockUp = p.getWorld().getBlockAt(loc);
if (block instanceof Ageable) {
Ageable crop = (Ageable) e.getBlock();
switch (crop.getMaterial()) {
case SUGAR_CANE:
if (blockUp.getType() == Material.SUGAR_CANE) {
ItemStack scane = new ItemStack(Material.SUGAR_CANE, 1);
p.getInventory().addItem(scane);
e.drop
}
break;
}
}
}```
No but you didn't understand or idk but infact the player joined and receives the item (the code from before) and there is an interaction.
This is the code, and whenever I break a sugarcane, it wont put 1 cane in my invenvory
what is the problem?
It's supposed to add a sugar cane into your inventory, but it wont.
When you create the item you add the PDC flag to it. be sure you apply the meta back onto the item after that is all done
any errors?
Ah yeah, look: ```java
NamespacedKey key = new NamespacedKey(plugin, "shop-key");
ItemStack chestGUI = new ItemStack(Material.CHEST, 1);
ItemMeta meta_chestGUI = chestGUI.getItemMeta();
meta_chestGUI.getPersistentDataContainer().set(key, PersistentDataType.DOUBLE, Math.PI);
meta_chestGUI.setDisplayName("Shop");
chestGUI.setItemMeta(meta_chestGUI);
yep
Ok I try.
perfect
you are sure that its instance of ageable?
Yeah thank you!
Maybe it's SUGAR_CANE_BLOCK
Sugarcane is ageable, right?
Location loc = block.getLocation();
loc.setY(loc.getY() + 1);
-> block.getLocation().add(0, 1, 0)
im not really sure
Don't think so
just check if its instance of sugarcane?
oh
It is Ageable somehow
but its not working so its not
Doesn;t list sugar cane
brb in a sec
bruh
he check the block
not the blockdata
thats the problerm
do if (block.getBlockData() instanceof Ageable ageable) {
odd, its not in Ageable
yeah, so weird
i guess when sugar cane has reached maximum age, they will grow another sugar cane on top
^
fun
Yes, but so does bamboo
Bamboo has an Interface adn is listed under Ageable
odd that Sugar cane doesn;t
Oh I see
nope, I don;t
bamboo is special, i guess
No clue, must just be a legacy thing.
Lagacy
oh bamboo have a leaves
?
thats what i am saying
I wonder how we get this "mix tape" https://hub.spigotmc.org/javadocs/spigot/org/bukkit/block/data/type/Fire.html
@quaint mantle
xd
yeah?
try this
if (block.getBlockData() instanceof Ageable ageable) {
if you have an older java version use do if (block.getBlockData() instanceof Ageable) {
Still does the damn thing, the problem is, it doesn't give me the item in my inventory..
Are you sure your code reached that?
try to debug your code
yeah
it disabled the drop
so it has to reach it
Can u paste your entire listener
?paste
i don't see any of your code that cancel the drop
lol please paste the whole code everytime
you're still comparing block with blockdata
bro
Change this part Ageable crop = (Ageable) e.getBlock();
You need to cast the BlockData not the Block
why you cannot copy?
It doesn't let you.
Honestly, since you're on 1.18.2 just use pattern variable.
Say I have an array of materials of length 50, if I wanted to get the item at percentage 50% it would get 25, this is my code:
int index = (int) (i / (max * materials.length));
index = materials.length - index - 1; // Reversing here since the array is in the opposite order (C B A)
return materials[index];
However its only getting the last 2 materials in the array regardless of percentage
for loop?
it is alwasy going to be teh last one as you are max * length)
Patterns are for java under 15 right ?
I'm using 17
index / (max * length)
should work
16+
^
patterns are J16+
^
double i = 56;
double max = 2;
int arrayLength = materials.length; // 50
int index = (int) (i / (max * arrayLength)); // 56 / 100
index = arrayLength - i - 1;
that's what it's doing
What is i
Its not relevant, you know it is a number from 0 to max * arrayLength - 1
Might as well update your Java since you're creating plugin for 1.18.2
So why is it 56
Yeah I'm doing it rn.
noice
Hmm
If materials.length is 50
Now it doesn't reach the code that it should execute.
mhm?
That's not what I'm asking
If you were to give i a more descriptive name
Wjat wpuld it be
Because it's not being used to iterate
distance?
@fallow violet I'll try to use the regular block check and not with instanceof ageable
well it technically is in my context
but yeah its distance from start you could say
(length / 100) * percentageYouWant
you need the #blockData(); @quaint mantle
(It ain't that, but its the closest explanation I can give)
I knew I was doing something wrong xD
Just realized I am doing index to percentage
rather than backwards
so it'd be
Ageable crop = (Ageable) e.getBlock().getBlockData();?
yes
yes finally
Okay yeah I'm just a bit not okay, thx!
its okayyy
Thx alot man!
<3
BungeeCord
Title Doesn't get send
String title = ChatColor.translateAlternateColorCodes('&',args[0]);
String subTitle = ChatColor.translateAlternateColorCodes('&', StaffChatCommand.getMessage(args,1));
Title tit = createTitle(title,subTitle);
for(ProxiedPlayer p : Main.getPlugin.getProxy().getPlayers()){
p.sendTitle(tit);
}
public Title createTitle(String title,String subtitle){
return Main.getPlugin.getProxy().createTitle().title(TextComponent.fromLegacyText(title)).subTitle(TextComponent.fromLegacyText(subtitle));
}
?main
Also use a getter
100%
for(ProxiedPlayer p : Main.getPlugin.getProxy().getPlayers()){
p.sendTitle(tit);
}
sender.sendMessage(prefix + "Odeslano!");
Also make sure your getPlayers actually contains the players
the "Odeslano" is being send
?
.
contains
why is getPlugin not a method
that kind of defeats the whole point
^
I used it like so cause it's static
Main.getPlugin???
but k
imma change it next time
yes
change it now lol
yes
?di
Guide to dependency injection: https://www.spigotmc.org/wiki/using-dependency-injection/
I don't see the difference in it
okk
but thats little off topic
any clues why it's not being send?
btw: use this: https://paste.md-5.net/otojutuxol.java
Solved:
forgot to set fadeIn stay and fadeout values
So If a tripwire hook is placed on a block and you break that block, the tripwire hook will also break. Is there any way to disable this update?
Probably the BlockPhysicsEvent
No I'm first
cancel the block break and break it manually without physics
Okay so whenever you /restart the server, it auto stops it, is there a way to make it so it boots up automatically again ?
configure teh start option in spigot.yml
@EventHandler
public void onBlockUpdate(BlockPhysicsEvent e) {
if(e.getBlock().getType() == Material.TRIPWIRE_HOOK) {
e.setCancelled(true);
}
}
Tried this but it's not working, am I doing it correctly?
Maybe start with debugging the block
I made it ./start.bat
and it opens up an empty cmd
._.
am i just 0iq ?
take off the ./
ooih
and be sure you actually have a start.bat
alright
java -Xmx8G -jar spigot-1.18.2.jar
PAUSE```
Use Aikars flags also you don't need - on nogui
i need it everytime lol
Nice tool
This is mine ```bat
for /f "tokens=" %%a in ('dir spigot.jar /b') do set p=%%a
if defined p (
echo Starting Server... %p%
java -Xms1G -Xmx1G -Dlog4j2.formatMsgNoLookups=true -jar -DIReallyKnowWhatIAmDoingISwear "%p%" nogui
) else (
echo No Spigot found!
)```
allows me to just drop any spigot jar in and it is executed
can you make choosing java version automatically?
I've not tried
is that shell or smth?
mobSpawnLoc.getWorld().spawnEntity(mobSpawnLoc.add(0,0,i),EntityType.ZOMBIE);```
This code summons Zombie at random positon from player but is it possible to do it at all diretions without writing code for every directions
locations are mutable
?
when you do .add(0, 0, i), it adds on to the last one
i know
but if i have to do it for all directions i have to write for everying possible directions player can looks
so is there any shorter method
so you’re just trying to spawn zombies all around someone?
i am bascally trying to summon my custom mobs around player
well what you have right now isn’t random
it is
i made a random variable and it summons it
when the random number is equal to my number
so i is a random number
for(int i=0;i<51;i++){
Location mobSpawnLoc = player.getLocation().add(0,0,1);
if(random.nextInt(19)+1==4){
mobSpawnLoc.getWorld().spawnEntity(mobSpawnLoc.add(0,0,i),EntityType.ZOMBIE);
}
}```
it will loop and add in i
if the random number matches it will spawn
otherwise it will skips
ok
How do I get when a player clicks on a specific area on their screen? I want to make custom menus to the side of the players screen, I want to know when the player interacts with said menus.
why not just add 2 different random numbers to the x and z?
you can’t do that with plugins
i think it requires modding but i am not sure
technically there’s 2 different clicks for the different sides of an inventory, but that’ll only work if you only need 1 different input option
and you would still need mods anyways for actually making a menu on the client
for(int i=0;i<51;i++){
Location mobSpawnLoc = player.getLocation().add(random.nextInt(50)+1,0,random.nextInt(50)+1);
}
}``` Like this?
well that’ll only add it in 2 different directions since it’s not negative
try like ThreadLocalRandom.current().nextInt(-50, 50)
Does anyone know a good way to spawn random loot in chests?
one last thing since they are spawning at player y it may spawn them underground so is there any way to avoid that since i cant use get highest y
Anyone know why this isn't sending anything to the player
player.sendMessage(ChatColor.translateAlternateColorCodes('&', "&b<est."));
thanks
My guess, the player object is stale as they have relogged and you maintained a reference
Huh?
from the little code you provided that is my best guess
where is that player coming from?
Can we add, update or delete elements in config.yml?
Yes
Obviously yes
How?
from the main instance getConfig();
#set(path, value)
if (plugin.getConfig().getString("players." + player.getDisplayName()) == null ) {
}
``` it is possible?
i actually forgot but if i set something in the config and get it right after that without saving, will it return it or not?
if (plugin.getConfig().contains("players." + player.getUniqueId()) {```
Any easy way to place a name tag/hologram above the player's head without using scoreboards?
i mean you can but itll be a bit laggy i would think to have an armorstand tracking your position, unless theres a better way idk
I just really dislike using scoreboards but I may have to bite the bullet.
Yeah but if I want to do : ```java
if (plugin.getConfig().getString("players." + player.getUniqueId()) == null) {
plugin.getConfig().set("players." + player.getUniqueId(), null);
plugin.getConfig().set("players." + player.getUniqueId() + ".level", 0);
plugin.getConfig().set("players." + player.getUniqueId() + ".xp", 0);
plugin.getConfig().set("players." + player.getUniqueId() + ".kills", 0);
}
To get something like this: ```yml
players:
beyptitloup:
level: 5
xp: 600
kills: 120
And it did not work.
if (!plugin.getConfig().contains("players." + player.getUniqueId())) {
plugin.getConfig().set("players." + player.getUniqueId() + ".level", 0);
plugin.getConfig().set("players." + player.getUniqueId() + ".xp", 0);
plugin.getConfig().set("players." + player.getUniqueId() + ".kills", 0);
}```
What is the best way for publish my project (private) as dependency then use it with gradle or maven?
didn't change what? If the section exists it will not change it
I mean I used jitpack, but private repo requires the subscription on jitpack
messages:
commands:
bienvenue: vient d'arriver sur le serveur
players:
It did not add the player.
If you are wanting to update it, simply doin't test if it exists
players.Program132 does not exist. ^
did you call save on teh config after adding it?
If i wanna backup mysql to a sqlite db should i just select * from table
Have a preparedstatement for the sqlite db and keep adding to batch for every result inthe resultset?
String message = event.getMessage();
Player plr = event.getPlayer();
event.setCancelled(true);
Bukkit.broadcastMessage("[" + plugin.getConfig().getString("players." + plr.getUniqueId() + ".rank") + "]" + "<" + plr.getDisplayName() + "> " + message);
``` We can check if the event come from a command (this event is AsyncPlayerChatEvent in this case).
How do people usually manage GUI configuration? I'm having trouble imagining how to keep track of what the player clicked on after theyve gone through like 2 or 3 inventories
uhh like what config settings they have changed?
for instance when I have a config which contains multiple of basically the same thing, like entity types and I want them to be able to configure that with a gui. for simplicity I would need one inventory which would let them choose the entity type to configure, then one to choose which setting to edit and then one where they can actually edit the setting. Would I make an object where I save those things and save it to a map keyed to the UUID?
It wouldn’t
It works.
just for a fun comparison, two types of packets sent to players. A packet of a changed itemstack and a packet of a moving armorstand, which one would be more intensive?
what's the best way for me to store various custom items that could be fished up? I was told yesterday to save a class instance into a map for each item, but i'm not sure how flexible that system is for items that require metadata
Hello what does system.currentitmemillis return and how would i go about converting it to different time units
i know it's simple multiplication, but i'm not sure what the output is like
unix?
and you can make a date of it by using new Date(long);
Well yes currentTimeMillis returns you the machines current unix time
^
Does someone know if there is a way to listen to Packet that the server is sending to the clients?
ProtocolLib has outgoing packet listeners iirc
But also for Packets from Server to Client?
that is outgoing
while(mobSpawnLoc.subtract(0,1,0).getBlock().getType()==Material.AIR){
mobSpawnLoc.add(0,0.5,0);
}```
This code checks if the block below the zombie is not air if it is then is subtracts the cords to avoid fall damage but it suffocates them instead
sending packets isn’t really intensive
unless you mean on the client
That code will also trigger if the zombie is high in the air
you’re subtracting 1 and then adding 0.5
any air under teh zombie will move the loc up half a block
so it ends up in a net value of -0.5
and after that the loop runs once again setting the location to 1 below
try adding .clone() to the condition
actually, yes it will move it down half a block
you subtract, so that modifies the actual location
it moves it down half a block as long as there is air and then when there's no air anymore, it removes 1 again
ok so it does the jobs now but i got 2 more problem they spawn half submerged and if i am in big cave then they fall from roof
then add 0.5 and do not use locations when they are in the air? lol what are you even trying to do
avoid them to spawn in air
it spawn at players y cords
so if player is at higher location
then they all just spawn in air
and i cant use get higest block
since it will only work at surface
well these are kind of 2 contradicting goals here
and why can't you just keep removing 1 from Y until there is no air anymore?
while(mobSpawnLoc.getBlock().getType().isAir() && mobSpawnLoc.getBlockY() > mobSpawnLoc.getWorld()getMinHeight()){
mobSpawnLoc.subtract(0,1,0);
}
mobSpawnLoc.add(0,0.5,0);```
also use .isAir instead of ==AIR
otherwise you will experience this "falling from the roof of caves" thing
If a player has opened his inventory and my plugin executes p.setItemOnCursor(ItemStack); then it's not working but if the player closes his inventory the item get's dropped
Does anyone know why or how I can fix it?
Improved so it stops at zero
Time in milliseconds since jan 1st 1970
World#getMinHeight()
ah true
So i've got this utillity, is this the best way to go about converting it?
(btw that method only exists since 1.16.4 or so)
I forgot world heights changed
why don't you just use the builtin TimeUnit class?
in java its builtin
TimeUnit.DAYS.convert(123456789, TimeUnit.MILLISECONDS);
this converts 123456789 milliseconds to days
sure you still have to do the "Best" part
i just wanted to mention that converting between all those units is builtin
What do you mean by "best"?
probably 1000 milliseconds would be 1 second while 60,000 would be one minute
and 998151259125762156 would convert it to the longest period, days in this case
@Override
public String format(double value) {
int seconds = (int) (value / 1000) % 60;
int minutes = (int) ((value / (1000 * 60)) % 60);
int hours = (int) ((value / (1000 * 60 * 60)) % 24);
int days = (int) ((value / (1000 * 60 * 60 * 24)));
String time = "";
if (days != 0)
time = days + " day" + (days == 1 ? "" : "s");
if (hours != 0)
time = time + (time.equals("") ? "" : " ") + hours + " hour" + (hours == 1 ? "" : "s");
if (minutes != 0)
time = time + (time.equals("") ? "" : " ") + minutes + " minute" + (minutes == 1 ? "" : "s");
if (seconds != 0)
time = time + (time.equals("") ? "" : " ") + seconds + " second" + (seconds == 1 ? "" : "s");
return time;
}
There's probably a better way to do that
@sacred mountain
Is it possible to add delay to item usage when i right click my custom item with right click, like enderpearl?
where it even shows that delay animation
you can only set cooldowns for the whole material
at least if you want to show the animation
well i use paper for that so i guess it would work even if it was whole material cause paper dont have any action in default minecraft
how would i approach that then?
I got no idea what you're talking about regarding paper now
oh you mean the material
declaration: package: org.bukkit.entity, interface: HumanEntity
player.setCooldown(Material.PAPER, 20)
that would mean a paper has a cooldown of 1 second
Cooldown on material aye very interesting lol
that would stop PlayerInteractEvent from firing when i right click it right?
probably it won't stop that event from being called
Set a cooldown on the specified material for a certain amount of ticks. ticks. 0 ticks will result in the removal of the cooldown.
Cooldowns are used by the server for items such as ender pearls and shields to prevent them from being used repeatedly.Note that cooldowns will not by themselves stop an item from being used for attacking.
you'll just have to try it out
is there anyway to get the amount of ticks passed since start
start of what?
oh i see, i want to use this for my paper which works like special teleport scrolls with nbt data, sometimes it eats 2 "scrolls" on holding mouse too long or server lag or smth, or so my players told me
server/plugin
so i would add little nice delay with this and it would prevent that from happening and would have nice little delay so people would not spam them for lag or smth
sure.
final Field currentTickField = Bukkit.getScheduler().getClass().getDeclaredField("currentTick");
currentTickField.setAccessible(true);
final int currentTick = currentTickField.getInt(Bukkit.getScheduler());
well i will try it thanks, i will report my results
just create a delay yourself instead
do a Map<UUID,Long> that stores when a player last used the item
if they use it again, check if their timestamp is at least 1 second old
oh.. um is there a way to avoid calling try/catch multipel times per tick?
ig i can start a repeating task at the start?
multiple times per tick? I doubt you need the current tick amount more than once per tick
I'd create a Cooldown class, like this or sth, idk havent tested, I wrote it in textedit
public class Cooldown {
private final Map<UUID,Long> lastUsages = new HashMap<>();
public void setCooldownNow(OfflinePlayer player) {
lastUsages.put(player.getUniqueId(), System.currentTimeMillis());
}
public boolean hasCooldown(OfflinePlayer player, double seconds) {
long lastValue = lastUsages.computeIfAbsent(player.getUniqueId(), __ -> 0L);
long minDelay = (long) (seconds * 1000);
return System.currentTimeMillis() - lastValue < minDelay;
}
}
so when a player uses your item, check if they hasCooldown(player, 0.5)
for 0.5 seconds
if it returns true, they cant use the item
if it returns false, use setCooldownNow to start a new cooldown from now on, and do your custom item code
Hi everybody, thanks for the patience reading this... I am new in creating plugins and now I have problems the setnodamageticks... i am just trying to do a "NoHitDelay" remake but also i want to customize the knockback for every hit.
The event listeners I am using is "EntityDamagedByEntity" but i don't know why the setNoDamageTicks completely disappeared and also if i want to take player entity by a command like Player p = (Player) sender; that's not working and this gave me variable like error....
Could you help me please?
how can i respond with code? I just paste here the link?
yes
error is this in red by intellij : "cannot find symbol"
i see
and if i click on the error this returns me to "p"
alright
first
You cast your Sender to a Player. Which is good. But you must do this AFTER the check, if is is a player. Right?
Is there something like #BlockData that checks if a crops is placed by a player ?
i dont think so
Do you understood?
so i have to repeat again if sender instance of player?
nope
in discord?
I will definitely copy this and save for future, thank you so much, but actually it seems that for this regular set cooldown worked fine
thanks for that too
apparently it doesnt stop the action but it also has method getcooldown(material) so it worked
if (pdc.has(nKey, PersistentDataType.INTEGER))
``` whats the return value if the given namespaced key is existent but is of datatype string?
This method will only return if the found value has the same primitive data type as the provided key.
will only return true*?
it'll throw an error
in the console?
well in the code lol
huh wdym
so
of course you can create new datatypes
but if you same something as integer, of course you cannot read that one as string
that iknow
xD
what i mean is only
if i provide this key
Hi, i needed disable Item move in my inventory / on lobby => dm me and solve it please 😉
you have to understand how PDC types work. They have two generic attributes, which are T and Z. The T is the "stored" primitive data class and Z is the "complex" data class.
E.g. if you store an itemstack as byte[] then you can only read it using other PDC types that also use byte[] as primitive type
if (pdc.has(new NamespacedKey(this, "version"), PersistentDataType.INTEGER))
``` -> and the object has a value of the namespaced key plugin:version but it is of type String, can the api handle this and return false or will it throw errors?
plsss
it will throw an exception because the primitive type for String is String and the primitive type for Integer is Integer
all the builtin data classes map the complex to the primitive type
so
how do i pre-check the data type of that value
before i compare it using .has()
i just need the proper error handling for this
because i didnt see in the api how to prevent data type violations then
you can't, at least not within builtin ways or without using NMS or craftbukkit code
I wonder why you would EVER need it though
after all you know what datatypes you use yourself
1st. iirc u can use cheats to inject nbt tags
2.nd what if items deprecate
and i use different data types after years
for example
im asking in advance for longlivibility
before
i dork it
here's the craftbukkit code. it gets the stored data from the actual NBT container, and then checks if it's instanceof the given PDC's primitive class
line 136
how would that work lol
if you use String as datatype, how would that ever be "false"
a String can't be false lol
if pdc key is either not found or of illegal data type return false
only return true if its found and legal
bruh as said
you cannot return false when you declare it to return <T> and T is String in this case
how would that work?
but .has() is a primitive bool?
oh you're talking about the has method
yea that will return false if the datatypes mismatches
thats what ive asked all the time xD
thats why i was so confused
obviously itll throw an error if i try to get the wrong type
well why didn't you just read the docs then lol
^
it's the second sentence in the docs
return what
xD
return ....
will only return if type is matched
and waht else?
crash?
and dont get me wrong im not trying to be anoying on purpose
just saying RecipeChoice.ExactChoice and shapeless recipes
xD
btw
public boolean setItemInteger(String key, int value)
{
if (this.is != null)
{
if (this.is.hasItemMeta())
{
ItemMeta meta = this.is.getItemMeta();
meta.getPersistentDataContainer().set(new NamespacedKey(main.getPlugin(main.class), key), PersistentDataType.INTEGER, value);
this.is.setItemMeta(meta);
return true;
}
}
return false;
}
public int getItemInteger(String key)
{
if (this.is != null)
{
if (this.is.hasItemMeta())
{
PersistentDataContainer pdc = this.is.getItemMeta().getPersistentDataContainer();
NamespacedKey nKey = new NamespacedKey(main.getPlugin(main.class), key);
if (pdc.has(nKey, PersistentDataType.INTEGER))
{
return pdc.get(nKey, PersistentDataType.INTEGER);
}
}
}
return -1;
}
yeah the javadocs are fucked up
also the @returns sentence is not a complete sentence lol
^^
idk lol
basically i wanted to know if this is type safe
yea thats why ive asked
so .has is safe to use on illegal types just returning false?
yes
kk
but as said it ONLY compares the primitive type
Does anyone know how to get the int of the selected hotbar slot of a player?
if you have for example a custom data type that uses String as primitive type, then checking for String will return true even when it's actually you custom data type, and vice versa
yea thats cool if i work with complex types i always serialize them and store them as bytestream anyway
then i write the handling methods myself
https://hub.spigotmc.org/javadocs/spigot/org/bukkit/inventory/PlayerInventory.html#getHeldItemSlot()
declaration: package: org.bukkit.inventory, interface: PlayerInventory
but since im still more used to C i use primitives most of the time tbh xD
ty!
getHeldItemSlot(), getItemInMainHand(), getItemInOffHand()
i prefer in main hand
if i wanna explicitly use the hotbar one
thanks, i like ternary operators heh
btw whats the standard convention for functions like this
public int getItemInteger(String key)
{
if (this.is != null)
{
if (this.is.hasItemMeta())
{
PersistentDataContainer pdc = this.is.getItemMeta().getPersistentDataContainer();
NamespacedKey nKey = new NamespacedKey(main.getPlugin(main.class), key);
if (pdc.has(nKey, PersistentDataType.INTEGER))
{
return pdc.get(nKey, PersistentDataType.INTEGER);
}
}
}
return -1;
}
returning -1, 0 or null?
in java*
xD
if not found*
I like to return OptionalInt in case the result does necessarily not return an int
so a wrapper that contains the info?
you cannot return null as int, you can only return null as Integer. Or use an OptionalInt as conclure said
sometimes 0 but if 0 belongs to the solution set your function returns then -1 might be a better alternative
just asking cause like in C -1 represents a fatal error, 0 represents correct execution xD
can yea
I'd use an OptionalInt or Integer. Probably OptionalInt is better since returning Integer, people could still store it as int ebcause auf auto-unboxing and then get NPEs
however none of my functions can use negative values but i cant declare unsigned ints
hm
maybe they will be able to have negative values in the future
just use an OptionalInt and done
kk ty xD
the only real advatage of returning 0 as default is that u can like check it like a bool
as it always returns true if its not 0
but iirc that doesnt work in java
Correct
how would i loop through all the items under the items: branch in this yamlconfiguration and then pass all the parameters for each item into a method i've setup?
Java is hardcore on its type system
c is very open u can basically typecast anything to anything esp primitives
for(String itemName : getConfig().getConfigurationSection("items").getKeys(false)) {
but errors are on u ofc
Yeah hence why people started using objective c instead
Would say Java is nicer if you don’t care about sloppy memory management
rust is better
har har har
so each itemName will be a map?

But yeah Rust also kind of overshadows cpp
or would i have to getConfigSection once i have each name?
cpp's real advantage is its freedom, something i struggle with in java
java has wayyyy more freedom than cpp
lmao
Freedom in terms of what? Memory management? Or just convenience features like generic varargs?
Myeah
typecasting
multilingual support
ive even embedded java code in my cpp programm accessing the JRE xD
RIP
Well one of Java’s selling point is that you get to disregard hardware related stuff
tho u can use pointers in java
Just beautiful abstractions and oo
struct User<'a> {
name: &'a str,
}
impl User<'_> {
fn has_balls(&self) -> bool {
self.name != "Timinator"
}
}
fn main() {
let user = User { name: "Timinator" };
println!("{}", user.has_balls());
}
their name is "Timinator", without r
Yes but Java abstracts away malloc and free for instance
for (String item : config.getConfigurationSection("items").getKeys(false)) {
config.getConfigurationSection(item).
}``` so once i've got each item, how would i get their values and put them into my method?
@EventHandler
public void onFurnaceBurn(FurnaceBurnEvent event)
{
Callbacks.disableFuel(event);
}
public static void disableFuel(FurnaceBurnEvent event)
{
ItemWrapper item = new ItemWrapper(event.getFuel(), null);
if (item.getItemStack() != null)
{
if (item.isFuel() != Access.TRUE)
{
Furnace furnace = (Furnace)event.getBlock().getState();
FurnaceInventory inv = furnace.getInventory();
if (inv.getViewers().size() > 0) inv.getViewers().get(0).getInventory().addItem(item.getItemStack()); else furnace.getWorld().dropItemNaturally(furnace.getLocation(), item.getItemStack());
inv.setFuel(new ItemStack(Material.AIR));
event.setCancelled(true);
}
}
}
``` this while looking weird to some maybe, is by no means inefficient just because i pass the event
You don’t even have to pay the slightest attention to that if you don’t want to
Yes as of now that is, but the underlying model for how pointers and memory management works could be shifted at any point of time and Java could still persist the change because of the abstractions it has offered
well this is the same for all classes actually
(It’s extremely unlikely but just as an example)
if that happens i can still take action
but its cleaner if it looks like this
I mean objects are references in Java
@EventHandler
public void onInventoryClick(InventoryClickEvent event)
{
Callbacks.onInventoryClickDisableEmeralds(event);
Callbacks.onInventoryClickTransmuteSmithing(this, event);
}
this is imo cleaner
than to smash everything in 1 function
even tho they have completly different purposes
Yes but that’s how you abstract away concerns to some extent
Anyway Java has no real notion of pointers in the language
It’s just pass by value**
The values are references
IIRC you can get the memory address of objects
Yep
and also directly set values at certain addresses
if use give function(&PlayerDeathEvent event) in C++ or just pass the event in java as of now defaults to the same
With the new memory api that should be possible (mfnalex)
xD
I was talking about sun.misc.Unsafe
Yep
huh
Altho its subject for removal
e.g. Unsafe.getUnsafe() (okay that only works with reflection) and then just putAddress, putLong, putChar, ......
tbh unless u write a memory hacking tool
I doubt it will ever be removed. It might be marked deprecated but it won't be removed in the next 10 years at least, it will break sooo soo soooo many things
or mod games on assembly level
u have virtually no reason to access mem addresses directly
yes you have
Is there an easy way to create menus?
when
Yes and no
if you care about performance really much for example
It’s not exactly the same but equivalent enough
not the same in the manner that it has to run trough the JRE layer yea
And then there’s the gc in Java which handles free for you
https://blogs.oracle.com/javamagazine/post/the-unsafe-class-unsafe-at-any-speed this explains stuff where Unsafe is currently (well, in 2020) is required
Yee
i cant tell u how much i was frustrated
to learn there aint conventional destructors in java
xD
finalize()
x)
at that point
i was writing my api to access my ini parser.dll
which passed its pointer to the JRE
Ough
which my JRE stores as integer
well long
since unsigned int32 in c++ is javas long equivalent
unsigned and signed sigh
One thing that Java messed up a bit
u mean
with the destructor?
finalize isnt safe to be called
xD
Yes but also signed and unsigned numbers
cant paste the whole file here
private long ptr;
public IniReader()
{
IniParser.Initialize(this);
this.ptr = initPtr();
}
finalize can be fixed by using Weak, Soft and PhantomReference with a ReferenceQueue
And also try finally
//Export for Java as .dll && .so
extern "C"
{
JNIEXPORT jlong JNICALL Java_IniReader_initPtr(JNIEnv* env, jclass cls) { return reinterpret_cast<std::uintptr_t>(new IniReader()); }
JNIEXPORT void JNICALL Java_IniReader_deletePtr(JNIEnv* env, jclass cls, jlong ptr) { delete (IniReader*)ptr; }
JNIEXPORT jboolean JNICALL Java_IniReader_openFilePtr(JNIEnv* env, jclass cls, jlong ptr, jstring str) { return ((IniReader*)ptr)->openFile(env->GetStringUTFChars(str, 0)); }
JNIEXPORT jboolean JNICALL Java_IniReader_closeFilePtr(JNIEnv* env, jclass cls, jlong ptr) { return ((IniReader*)ptr)->closeFile(); }
JNIEXPORT jboolean JNICALL Java_IniReader_jumpToHeaderPtr(JNIEnv* env, jclass cls, jlong ptr, jstring str) { return ((IniReader*)ptr)->jumpToHeader(env->GetStringUTFChars(str, 0)); }
JNIEXPORT jboolean JNICALL Java_IniReader_getNextLinePtr(JNIEnv* env, jclass cls, jlong ptr) { return ((IniReader*)ptr)->getNextLine(); }
JNIEXPORT jboolean JNICALL Java_IniReader_isKeyValuePtr(JNIEnv* env, jclass cls, jlong ptr, jstring str) { return ((IniReader*)ptr)->isKeyValue(env->GetStringUTFChars(str, 0)); }
JNIEXPORT jstring JNICALL Java_IniReader_getKeyValuePtr(JNIEnv* env, jclass cls, jlong ptr) { return env->NewStringUTF(((IniReader*)ptr)->getKeyValue()); }
JNIEXPORT jstring JNICALL Java_IniReader_getValueStringPtr(JNIEnv* env, jclass cls, jlong ptr, jint index) { return env->NewStringUTF(((IniReader*)ptr)->getValueString(index)); }
JNIEXPORT jint JNICALL Java_IniReader_getValueIntPtr(JNIEnv* env, jclass cls, jlong ptr, jint index) { return ((IniReader*)ptr)->getValueInt(index); }
JNIEXPORT jfloat JNICALL Java_IniReader_getValueFloatPtr(JNIEnv* env, jclass cls, jlong ptr, jint index) { return ((IniReader*)ptr)->getValueFloat(index); }
}
xD
thats how i made java handle pointers
🌞
hahaha
return reinterpret_cast<std::uintptr_t>(new IniReader());
``` xD this returns its own instance ptr as unsigned int
that then can be stored as long by the JRE
^^
what the fuck
why xD
yk as a rust user i feel like i should somehwat understand this but i have no idea what this does
i taught java the existence of pointers
cast an ini reader to an unsigned int pointer
no
i instantiate a new ini reader
and then typecast its pointer into an int
and return this int to the JRE
so the JRE side code can store the pointer as integer
^here
ill read trough it
some might call it magic xd
i wrote that for my plugins to access their ini parser from a dll
but my hostprovider blocks binary code execution
With Unsafe you can basically do your pointer stuff that you seem to like lol
I only read until the end of the AtomicCounter example
Hello !
I'm looking for a good inventory framework 👍
All that I find are no longer maintained
I have a fork of that for 1.18 including a proper maven artifact
np
how do i get the config file from a class that isn't the main class
How would I go about installing the mapped version of spigot with build tools?
YourMainClass.getInstance().getConfig();
just create that instance in your main
BuildTools installs it automatically. Just run buildtools with the --remapped flag
advertisement for his website -_- what did i expect lol
done, and I've deleted the previous version of spigot. I'm using maven, so do I need to change anything inside the dependency tags to update to the remapped version?
thats not even bad
yeah you need to set the classifier to remapped-mojang and also add a huge config to the specialsauce plugin. here's another blog post about how to use remapped:
https://blog.jeff-media.com/nms-use-mojang-mappings-for-your-spigot-plugins/
Would anyone know how to make a scoreboard, where you can change the words of it using a command?
do I even need to add the whole <build> thing if I'm just adding the dependency tags instead
it's in the official spigot repo, did you add that?
try clicking on "maven" -> the "m" button -> enter mvn clean package -U
see if that fixes it
do I need the build tag though
yes
was just a joke :(
you cannot simply use mojang mappings in your plugin. you can only use it in your code, and let this plugin translate it back to the "obfuscated" names the spigot.jar is using
sometimes there's even people claiming "ugh I don't click on random links, they can contain viruses" so I wasn't sure if you're serious lol
nope
send the full maven log
to get the FULL log, you have to click the uppermost thing on the left next your the console output
and yeah then copy everything from the console
it has worked fine
your intelliJ is just a bit stupid. Do File -> Invalidate Caches -> Invalidate and Restart, then wait a bit
Okay, everything works & all, but I'm trying to parse an item's nbt to an item stack, and seems to me that on the remapped version classes such as MojangsonParser and NBTTagCompound have been renamed. Do you happen to know what they are?
check out the source of CraftPersistentDataContainer, there you'll see how they are called
IIRC then NBTTagCompound is just CompoundTag or sth like that
Hey there,
does anyone know a simpler way to get the duration of something in seconds with 2 decimals? I currently use the following, which works fine, but seems kinda ugly
basically yeah you can just type the name of some CraftBukkit class that is likely to access the NMS classes you need, press Cmd+B or Ctrl+B to view it's source, then search a bit. So yeah, NBTTagCompound is actually net.minecraft.nbt.CompoundTag
String rounded = String.format("%.2f", 0.12345);
What's the purpose of the asString and asEdited?
You can just have:
long duration = whatever;
double seconds = duration/1000.0;
DurationFormat format = new DurationFormat("#.##");
return format.format(seconds);
Note the .0 on the 1000 is necessary as you need it as a double.
I'm also assuming your duration starts out as milliseconds.
I used System.nanoTime(); and tried converting it in seconds by dividing it by 1.000.000.000, but this always got me something like 4.0 seconds or 5.0 seconds and not 4.35
Yh u gotta add a .0 on the end otherwise it'll come out as a long.
why not just use this lol
long/long = long, long/double = double.
it's a one liner
what's actually the difference? coz why would they create DecimalFormat if u could just use String.format
Or does DecimalFomat just provide more granularity
I have to convert it from nanoseconds to seconds first
Your nanoseconds -> seconds issue is just that ur dividing a long by a long. That'll give you a long.
When you divide it, add a .0 on the end so you're doing a long divided by a double.
yeah so? then just divide it through 1000*1000 or whatever
idk. String.format uses a java.util.Formatter
just case the second parameter
double myseconds = something / (double) 10000000
So I have this now
double duration = (this.end - this.start) / 1000000000.0;
this.end and this.start being long values
yeah and now just put that into
String.format("Duration: %.2f seconds",duration);
^^
Will try, give me a second
Ok looks like the difference with DecimalFormat is it accounts for system locale, e.g 1.0 vs 1,0 and currency symbols.
private static final long SECOND_IN_NANOSECONDS = TimeUnit.SECONDS.toNanos(1);
@SneakyThrows
public static void main(String[] args) {
long startTime = System.nanoTime();
Thread.sleep(2500);
long differenceInNanoSeconds = System.nanoTime() - startTime;
double differenceInSeconds = differenceInNanoSeconds / (double) SECOND_IN_NANOSECONDS;
System.out.println(String.format(Locale.ENGLISH,"Duration: %.2f seconds",differenceInSeconds));
}
this prints out "Duration: 2.50 seconds"
yeah check out my code above, just pass Locale.ENGLISH if you care about this
It works, but the thing is I'm only getting values like 1.80 seconds, 2.35 seconds, 3.45 seconds etc, not smth like 4.27 seconds
i don't get it
where is the difference between 1.80, 2.35, 3.45 and 4.27?
can u print out the difference (in nanos) to check the raw value.
yes wait a sec
it works fine for me.
public class Test2 {
private static final long SECOND_IN_NANOSECONDS = TimeUnit.SECONDS.toNanos(1);
@SneakyThrows
public static void main(String[] args) {
long startTime = System.nanoTime();
Thread.sleep(2510);
long differenceInNanoSeconds = System.nanoTime() - startTime;
double differenceInSeconds = differenceInNanoSeconds / (double) SECOND_IN_NANOSECONDS;
System.out.println(String.format(Locale.ENGLISH,"Duration: %.2f seconds",differenceInSeconds));
}
}
Same as above but it prints "Duration: 2.51 seconds". Which is totally accurate, I've did Thread.sleep for 2510ms
What wakes a sleeping thread?
usually mom
Seems abt right
ye seems like it's working, I'm just surprised cause it ends with 0 or 5 very often
for example an InterruptedException
well remember that ticks are always 1/20th of a second
so depending on what you do, it makes sense that it's * 0.05 very often
np :)
np :3
Recently I found out that there's no way to detect a middle-click in an inventory of a player in survival gamemode anymore
I had to change some plugins to shift-left-click 😦
that's correct, IF the slot is empty
it should work fine on non-empty slots IIRC
although I don't 100% remember that
yeah RIP for my ChestSort
you changed it to shift left click too?
idk there were some other click types but I found shift left click one of the better options
wait it doesn't seem to even send it when on an item
yes seems like it doesn't
well that sucks
I tried yesterday and I didn't get it working
yh the client sends no packet
i still hope that it comes back in 1.19
was kinda annoying me when I updated some plugins from older versions to 1.18+
same!
This might be a dumb question but can you set the default of a switch operation to just break; ?
sure
sure
perfect
you can also use weird names for your enums
public enum $$ {
__;
public $$ $$($$ this) {
switch (this) {
case __:
default:
break;
}
return __;
}
}
no one needed to witness this
obfuscation joined the game
imagine using this in your project
i enjoy my enhanced switches :)
xd
I often use __ in lambdas if I don't actually need that parameter
I just call them unused.
for example
long lastValue = lastUsages.computeIfAbsent(player.getUniqueId(), __ -> 0L);
.queue(unused -> channel.getManager().setLocked(true).queue());
it was explained like this in a java bbook I read so I sticked to it
they said another way would be to use the type, e.g.
I want to replace the blocks around the player, like that
Would the most efficient way be to get the blocks within a radius of 1 around the player?
long lastValue = lastUsages.computeIfAbsent(player, OfflinePlayer -> 0L);
I only know the method with 3 for loops for x y and z
in this method 2 loops for x and z
imagine writing 8 lines with the relative positions
ikr
ugh too many people do that
no way
and they copy paste their whole code again to add for example the next 2 instead of next 1 blocks
it pains me to know that happens
same
I think and hope most people improve stuff like that over time
and get more efficient
it wont
those people end up working for ubisoft
I've looked around and I'm kinda stuck. Is there a way to prevent a dependency from unloading until all it's dependents have completely unloaded?
Hello, i'm trying to load a world here is the code:
String[] worldNames = { "", "_end", "nether"};
World.Environment[] worldType = {World.Environment.NORMAL, World.Environment.THE_END, World.Environment.NETHER};
for (int i = 0; i < worldNames.length; i ++) {
int finalI = i;
new Thread(() -> {
World world = new WorldCreator(game.getId()+worldNames[finalI])
.environment(worldType[finalI]).createWorld();
Bukkit.getServer().getWorlds().add(world);
}).start();
System.out.println(game.getId()+worldNames[i]);
}
The proble is that when i load the world it take a lot of time and lags the whole lobby
I have a plugin that provides kotlin-stdlib and exposed for my plugins and it seems to unload before it's dependents :P
Alrighty, I'll give that a try!
Does anyone know a shortcut to switch from a tab to another one which is on another split window in intelliJ?
it's on one page
if i have a playerinteractevent and i do ItemStack item = event.getItem(); then modify item, will later doing event.getItem() return the modified item or does .getItem() clone the event item
I mean when you rightclick on a tab you can choose to split it
hmmm, not sure. i think intellij has a shortcuts section in preferences
I'll look into it, thanks!
np! im gonna take a quick look too
@iron glade In preferences go to Keymap and search "split". I saw a few things that might be what you wanted
Hm, all I found to work is alt + left/right arrow key to switch tab
hmmmm
but I can't jump into the other window which was split
Preferences -> Keymap -> Mainmenu -> Window -> Editor tabs
thats what i found
im on mac so my key combinations are different
Yes same, but nothing in that list sounds like an option to switch between windows 😦
I have no idea
damn
Think it returns the modified item
that was he best idea i had
dw I guess I'll just use the mouse to click on the other window
it should unless it isnt saved
rip. srry
dw man, thanks for trying to help < 3
np < 3
if i get it correctly, keymap/main menu/window/editor tabs/ goto next/prev splitter
any way to remove the blue "Tools"? https://gyazo.com/0bfa6bc301c8c8cdb9399e8b10302090
nope
lmao
those aren't item tags or shit, but rather "tags" that are added by the client to not be changeable
or removeable
short: no, you can't remove it without a clientside mod
f3 + h probably
nah its not that
oh
oh ok
tho i wonder... aren't those blue tags in creative only?
im not at my pc rn so i wasnt sure
im in creative rn
yeah they are
so you know what section its from