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

2014/6/6

Avoid collision with walls

sansarion sansarion

2014/6/6

#
Hello, im trying to make a single player tron game.Here is an example i found link What im trying to do is to avoid hitting the walls ( on the actor that i cant control ,who is being played from the computer).Here is the code that i have so far
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

public class PlayerPink  extends Actor
{
    private GreenfootImage pink = new GreenfootImage("PinkPlayer.jpg");
    int lastMovement = Greenfoot.getRandomNumber(5);
    int newMovement;
    public void act()
    {
        moveTron();
        die();
        leaveTrail(getX(), getY());
    }
   
     /** This method allows the player to interact with the actor.
     * It detects when and which button is pressed
     * The actor will move in the direction accordingly.
     * This is done by connecting the button keys with a command
     * "last pressed", which allows it to repeate infinitely.
     */
    public void moveTron()
    {
        int z = 3;
               int decideToTurn;
        decideToTurn=Greenfoot.getRandomNumber(100);
        if (decideToTurn<3)
        {
            newMovement = Greenfoot.getRandomNumber(4);
               
                if ((java.lang.StrictMath.abs(newMovement-lastMovement)!=1) || (newMovement*lastMovement==2)) 
                {
                    lastMovement=newMovement;
                }
            }
           switch (lastMovement) {
            case 0: setLocation(getX() - z, getY());     
                     break;
            case 1:  setLocation(getX() + z, getY());                   
                    break;
            case 2:   setLocation(getX(), getY() - z);
                     break;
            case 3:  setLocation(getX(), getY() + z);
                     break;
        default:     break;
    } 
    
    
}

    /** This method checks whether or not Pink is in contact with Blue or with a trace.
     *  If it is true, then the scenario will stop.
     */

    public void die()
    {
        Actor p = getOneObjectAtOffset(0,0,null);
        if (p!=null)
                 {
            getWorld().addObject(new GameOverText("PINK"), 400, 300);         
            Greenfoot.stop();
         }
    }

     
    /** This method requests for the world to add a static actor that is a replica of this one wherever it goes. */
    public void leaveTrail(int x, int y)
    {
    

         getWorld().addObject(new TrailPink(), x, y); 
        
     
    }
}
I tried some things but i just managed to move it diagonally . Thank you in advance.
You need to login to post a reply.