This site requires JavaScript, please enable it in your browser!
Greenfoot back
comfortablyNumb
comfortablyNumb wrote ...

2019/11/5

Stop player from moving after intersecting actor

comfortablyNumb comfortablyNumb

2019/11/5

#
In my player class i have a public static boolean canMove if its true the player can move. I want to have it so that when the actor intersects a specific actor that this variable is set to false for a specified amount of time and then set it back to true. i tried doing this wtih this function
protected void collideWithPlayer() 
    {
        if(this.isTouching(player.class)){
            player.canMove = false;
            long start = System.currentTimeMillis();
            for(int i = 0; i < 5; i++){
                Thread.sleep(3000); //unreported exception 
                                   //java.lang.interuptedexecution; must
                                   //be caught or declared to be thrown
            }
            player.canMove = true;
        }
    }
it returns the error in the comment on Thread.sleep(3000). correct me if im wrong but using this method if there were no error would result in all of greenfoot becoming unresponsive, which i don't want just want the player to not be able to move for 3 seconds while everything else continues to move
danpost danpost

2019/11/5

#
Never use thread ops in greenfoot -- and only use Greenfoot.delay when you want the entire scenario to pause for a specified amount of time. It would be better to have the player detect this actor and the canMove field should not be a static one. How can one tell whether a field should be static or not? Ask what happens if you have more than one instance of the class (two or more players, in your case). If the state (field value) is at all times the same for all instances, then you can make the field static. In your case, I doubt you would want all to not move if just one was found touching this actor. The value of the field is independent for each instance, so ... do not use static here. Add a timer field and set it to 180 when touching the actor (I will call it frozen):
private int frozen;
// in act
if (isTouching(??whatever??.class)) frozen = 180;
At the beginning of the player act method, add something like the following:
if (frozen > 0 && --frozen > 0) return;
With this, the player will take no action until the timer reaches zero.
You need to login to post a reply.