I'm working on an item that, when right-clicked, pushes back entities in a circle around the player. However, I want the entity to be pushed back following the same line; right now, the entities are pushed back into the closest corner. Additionally, I don't want the item to push entities through walls(so setting entity.posX/entity.posY directly or using entity::moveTo won't work). Here's the code that I have now:
@Override
public ActionResult<ItemStack> onItemRightClick(ItemStack itemStackIn, World worldIn, EntityPlayer playerIn, EnumHand hand) {
AxisAlignedBB aabb = playerIn.getEntityBoundingBox().expand(playerIn.posX + range, playerIn.posY + range, playerIn.posZ + range);
List<Entity> entityList = worldIn.getEntitiesWithinAABBExcludingEntity(playerIn, aabb);
for (Entity entity : entityList){
if (entity instanceof EntityLiving){
rebukeEntityFromPlayer((EntityLiving) entity, playerIn);
}
}
return super.onItemRightClick(itemStackIn, worldIn, playerIn, hand);
}
private void rebukeEntityFromPlayer(EntityLiving entity, EntityPlayer player){
//Creates xy plane with player at center by getting the directional distance between the coords of the entity and the player
double adjX = entity.posX - player.posX;
double adjZ = entity.posZ - player.posZ;
//Creates a triangle to describe the distance between the entity and player
double startSideA = adjX;
double startSideB = adjZ;
double startHyp = Math.sqrt((Math.pow(startSideA, 2) + Math.pow(startSideB, 2)));
//Scales the triangle to get the point the entity should be pushed to
double scaleFactor = range/startHyp;
if(scaleFactor <= 1){return;}//stops spell if entity is already out of target area.
double scaledSideA = startSideA*scaleFactor;
double scaledSideB = startSideB*scaleFactor;
double desiredPosX = adjX + (scaledSideA - startSideA);
double desiredPosZ = adjZ + (scaledSideB - startSideB);
if(Math.abs(adjX) < Math.abs(desiredPosX)){
if(desiredPosX >= 0){
entity.motionX = 3;
} else if(desiredPosX < 0){
entity.motionX = -3;
}
}
if(Math.abs(adjZ) < Math.abs(desiredPosZ)){
if(desiredPosZ >= 0){
entity.motionZ = 3;
} else if(desiredPosZ < 0){
entity.motionZ = -3;
}
}
}
Additionally, here are some images to help convey my problem: Ideal Scenario, Current scenario