In one of my mods, I have a mysterious stranger entity appear randomly but wanted it to be in front of the player so that the player noticed. The code I used was (note this was 1.7.10 but should mostly be the same, although Vec3 is now called Vec3d, worldObj is now called world and so forth):
Vec3 playerLookVector = player.getLookVec();
EntityMysteriousStranger entityToSpawn = new EntityMysteriousStranger(worldObj);
double spawnX = player.posX+5*playerLookVector.xCoord;
double spawnZ = player.posZ+5*playerLookVector.zCoord;
double spawnY = worldObj.getHeightValue((int)spawnX, (int)spawnZ);
// check to ensure there is open area for stranger to spawn, not underground
if (worldObj.canBlockSeeTheSky(MathHelper.floor_double(spawnX), MathHelper.floor_double(spawnY), MathHelper.floor_double(spawnZ)))
entityToSpawn.setLocationAndAngles(spawnX, spawnY, spawnZ,
* 360.0F), 0.0F);
What it basically does is use the player look vector and multiply by the distance you want and add that to the player location. For the z value though it checks for the top block in the world at that x, y location and furthermore checks that it is in open to the sky (but you might not need that part for your purpose).
Anyway, the main key is that the player has a look vector which you can use.
The Meaning of Life, the Universe, and Everything.
Ok, thanks! I'm gonna have to port my mod to 1.12 though, onceI have a couple more things done. It seems like the code changes are as bad as 1.7.10>1.8! Anyway, I'll get back to you if I have any trouble.
Well, the closeness is the number 5 you're multiplying. So use a smaller number if you want it closer.
If you don't want it on top of certain things like trees, you need to write extra code to check for a more suitable position. Like you would check if the block at that location was leaves and if it was you'd have to loop to lower locations to see if you could find a regular place to place it.