[Quick Tip] Teleporting using pitch and yaw

Discussion in 'Resources' started by Mr360zack, Apr 6, 2014.

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

    Mr360zack

    Ok, so I've seen quite a few people (aswell as myself :p) have trouble with this, so I'm going to make a quick thread on how to do it.

    In this example, I'm going to make a getSpawn() method that will return the spawn location from the config

    Code:
    public Location getSpawn(){
    Location loc = new Location(null, 0, 0, 0);
    //setting a null location temporarily
    
    if(getConfig().get("spawn.world")!=null){ // null check
    loc.setWorld(Bukkit.getWorld(getConfig().getString("spawn.world")));
    }
    
    if(getConfig().get("spawn.x")!=null){
    loc.setX(getConfig().getDouble("spawn.x));
    }
    
    if(getConfig().get("spawn.y")!=null){
    loc.setY(getConfig().getDouble("spawn.y));
    }
    
    if(getConfig().get("spawn.z")!=null){
    loc.setZ(getConfig().getDouble("spawn.z));
    }
    
    if(getConfig().get("spawn.pitch")!=null){
    loc.setPitch((float) getConfig().getDouble("spawn.pitch));
    }
    
    if(getConfig().get("spawn.yaw")!=null){
    loc.setYaw((float) getConfig().getDouble("spawn.yaw));
    }
    
    //if any are null, return null.  When using getSpawn() make sure to do if (getSpawn() != null){
    if(loc.getX()==null||loc.getY()==null||loc.getZ()==null||loc.getWorld()==null){
    return null;
    }
    
    return loc;
    
    }

    I wrote this on my iPhone, if you notice any errors or mistakes just please let me know .

    If you have any questions or problems just tell me.
     
  2. why dont just this?
    Code:Java
    1.  
    2. try{
    3. Location loc = new Location(null, 0, 0, 0);
    4. loc.setWorld(Bukkit.getWorld(getConfig().getString("spawn.world")));
    5. loc.setX(getConfig().getDouble("spawn.x"));
    6. loc.setY(getConfig().getDouble("spawn.y"));
    7. loc.setZ(getConfig().getDouble("spawn.z"));
    8.  
    9. p.teleport(loc);
    10. p.getLocation().setPitch((float) getConfig().getDouble("spawn.pitch"));
    11. p.getLocation().setYaw((float) getConfig().getDouble("spawn.yaw"));
    12. }catch(Exeption e){
    13. }
    14.  



    that dont work, use instead the null, null, null, null this: null, 0, 0, 0
     
  3. Offline

    Mr360zack

    Oh yeah, forgot about that thanks.
     
  4. Offline

    gyroninja

    The reason why you wouldn't do is that you would be throwing exceptions that are not needed. Checking for null is less expensive than throwing a npe. Alternatively you should specify default values when you are reading the config as to avoid it ever throwing an npe from a missing value.

    You can specify default config values by using for example getString("stringkey", "default string")

    Side note: Why don't you store the pitch and yaw in the location object itself.
     
Thread Status:
Not open for further replies.

Share This Page