Crops targeting

Discussion in 'Plugin Development' started by Anarchy_, Mar 7, 2021.

Thread Status:
Not open for further replies.
  1. Offline

    Anarchy_

    Hello developers!
    Today I want to tell you how to cancel the breaking of the wheat block. (Sorry for my English, I try to write correctly)
    Here is the code:
    Code:
    //  we're need a PlayerInteractEvent.
        @EventHandler
        public void onPlayerInteract(PlayerInteractEvent event) {
    //        output the block that you interacted with
            System.out.println(event.getClickedBlock().getType());
    //        checking the action with this block
            if (event.getAction().equals(Action.PHYSICAL)) {
    //            if the action is physical, output 1 (for debug)
                System.out.println(1);
    //            we check the type of the block that we interacted with
                if (event.getClickedBlock().getType().equals(Material.SOIL)) {
    //                yeah, block type is soil, printing 2 to console
                    System.out.println(2);
    //                checking: player == null ?
                    if (event.getPlayer() != null) {
    //                    yes, player != null, printing 3
                        System.out.println(3);
    //                    cancel the action
                        event.setCancelled(true);
    //                    done!
                        System.out.println(4);
                    }
                } else {
    //                if our action is not associated with soil, we will get a Nullpointerexception error, so we prevent it.
                    System.out.println(event.getClickedBlock().getType());
                }
            }
        }

    If I helped you, be active. This topic is very common and many people ask this question.
    Thank you all for reading and enjoy your coding!
     
  2. Offline

    Wick

    Keep in mind PlayerInteractEvent#getPlayer is @NotNullable so it will never return null and thus your check is unnecessary. Also, your code seems to benefit greatly from negative checking to reduce if statements branching on if statement's.

    Code:
        @EventHandler
        public void onInteract(PlayerInteractEvent event) {
    
            if (!event.getAction().equals(Action.PHYSICAL) {
                return;
            }
    
            if (!event.getClickedBlock().getType().equals(Material.SOIL)) {
                return;
            }
    
            event.setCancelled(true);
    
        }
    That's not true.
     
  3. Offline

    Anarchy_

    Ah, ok
     
    Last edited: Mar 7, 2021
  4. Offline

    Newdel

    Why would you even do it with player interact event...
     
  5. Offline

    davidclue

    That's oddly specific a wheat block and I don't know why you wouldn't just use a BlockBreakEvent because then you could simplify your code down to 2 lines.
     
Thread Status:
Not open for further replies.

Share This Page