Search code examples
javaibm-doors

How to make a function to close a door when the player is not near it?


So im making a wolfenstein 3d copy in Java and i've done a door list to change from 1 (closed) to 2(open) and i would want to make 2 to 1 when the player is not near it ive got 2 variables for the player(yPos, xPos) and 2 for the door(row,column)


Solution

  • First of all, I think that "ibm-doors" is not a good tag for your question ^^

    Actually, this is a math question. You can calculate the distance between the player and the door with this formula (you may adapt the variable names and operators to your needs):

    playerDoorDistance = sqrt((player.xPos - door.xPos)^2) + (player.yPos - door.yPos)^2)
    

    where sqrt is the square root of what is between brackets, and ^2 is the square of what is between brackets.

    Once calculated, you can just check that this distance is greater than a value of your choice to close the door.

    If you prefer something more simple and that requires less calculation, you can just verify that abs(player.xPos - door.xPos) and abs(player.yPos - door.yPos) are greater than your chosen value (abs is the absolute value of what is between brackets) to close the door. It will verify that your player is outside a squared box around the door.

    If you want no math at all, you can check this, which is the same as above (you may also adapt it to your needs):

    if (player.xPos - door.xPos > chosenValue || door.xPos - player.xPos > chosenValue || player.yPos - door.yPos > chosenValue || door.yPos - player.yPos > chosenValue)
    then closeTheDoor()