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

2015/12/29

SEND HELP: ACTOR IN MOTION PROBLEM

fayechu fayechu

2015/12/29

#
Hello! We have a homework due this new year's eve and I need help! I need pikachu to face right when pressing the right key, to face left when pressing left key, to face up when pressing the up key and to look down when pressing the down key. Also, i need it to stop animating when no key is pressed and only move when a key is pressed. Please send help, I'd be really thankful. This is what i got so far, thanks in advance!
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

/**
 * Write a description of class Pikachu here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */

public class Pikachu extends Actor
{ 
    /**
     * Act - do whatever the Pikachu wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */

    GreenfootImage[] images = new GreenfootImage[7];
    private int imageNumber;
  
    public Pikachu()
    {
        setImage("7.png");
        {
            for( int i=1; i<images.length; i++ ) 
            {
                images[i] = new GreenfootImage( "" + i + ".png" );
                System.out.println(i);
            }
        }
    }

    public void act() 
    {
        animate();
        pikachuMove();
    }

    public void animate()
    {
        imageNumber = ( imageNumber + 1 ) % images.length;
        setImage( images[imageNumber] );
        Greenfoot.delay(5);
    }

    public void pikachuMove()
    {
        if (Greenfoot.isKeyDown("left"))
        {
            turn(-3);
            setRotation(-180);
            move(10);
            
        }
        if (Greenfoot.isKeyDown("right"))
        {
            turn(3);
            setRotation(360);
            move(10);
            
        }
        if (Greenfoot.isKeyDown("up"))
        {
            setRotation(270);
            move(10);
            
        }
        if (Greenfoot.isKeyDown("down"))
        {
            setRotation(90);
            move(10);
            
        }
    }
}

danpost danpost

2015/12/29

#
First, to avoid moving diagonally, you need to change subsequent 'if's to 'else-if's in the 'pikachuMove' method. Then, instead of calling 'animate' from the 'act' method, call it from each one of the key 'if' blocks in the 'pikachuMove' method (since you only want to animate when moving).
fayechu fayechu

2015/12/29

#
I'm sorry, I'm a beginner in greenfoot. I quite don't understand what you're trying to say. Can you put it in codes? THANK YOU A BUNCH! :)
fayechu fayechu

2015/12/29

#
REALLY REALLY APPRECIATE YOUR REPLY!
fayechu fayechu

2015/12/29

#
:)
You need to login to post a reply.