Knockback a player in opposite direction to a block

Discussion in 'Plugin Development' started by Victini151, Sep 10, 2012.

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

    Victini151

    Hey there,
    i'm developing a plugin in which you should be knockbacked after passing a square of blocks.
    You should be knockbacked in opposite direction to the block, but all my code does, is knocking back a player to one corner of the square (the block you should be knockbacked opposite to is inside this square).

    Code:
    //multiplication factor
    double mult = -1.0;
                       
    //get block z
                        int z1 = this.getConfig().getInt("middlez");
    //get player z
                        int z2 = (int) e.getPlayer().getLocation().getZ();
    //get block x
                        int x1 = this.getConfig().getInt("middlex");
    //get player x
                        int x2 = (int) e.getPlayer().getLocation().getX();
    //get z distance
                        int n1 = z1 - z2;
    //get x distance
                        int n2 = x1 - x2;
                       
    //get player direction
                        Vector v = e.getPlayer().getLocation().getDirection();
                        v.setY(0);
                       
    //get direction to knockback to
                        if (n1 < 0) {
                            v.setZ(-1);
                        } else if (n1 >= 0) {
                            v.setZ(1);
                        }
                        if (n2 < 0) {
                            v.setX(-1);
                        } else if (n2 >= 0) {
                            v.setX(1);
                        }
                       
    //apply knockback by changing velocity
                       
                        e.getPlayer().setVelocity(v.multiply(mult));
    (In this code i already have checked if the user passed the outer line of the square, its inside onPlayerMove)

    Thanks, Victini151
    (Sorry for my bad english, i'm german :/)
     
  2. Offline

    andf54

    Here is what I used in my plugin. It pushes back entities from the player. Just replace the players location with blocks location.
    Code:
    /**
    * Pushes away an entity from the player
    *
    * @param entity entity
    * @param speed speed
    */
    public void pushAwayEntity(Entity entity, double speed) {
    // Ignore if the player isn't online:
    if(!isOnline()){
    return;
    }
    // Get velocity unit vector:
    Vector unitVector = entity.getLocation().toVector().subtract(player.getLocation().toVector()).normalize();
    // Set speed and push entity:
    entity.setVelocity(unitVector.multiply(speed));
    }
    
     
Thread Status:
Not open for further replies.

Share This Page