Sign in to follow this  

Sprite movement issues [SOLVED]

This topic is 4284 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I'm having problems trying to get my sprite to move around my tile layer. For some reason, I'm getting the nagging suspicsion that it might be due to the fact that my keypresses are not invoking the methods that move the sprite around. I'm not sure about this, but is it feasible to use both keystates and keypresses at th3e same time and would that help in invoking the sprite movement methods? Also, since my player sprite is five frames (one for standing still and the rest for moving in a given direction), how can I juggle frame sequences when moving and standing still. In other words, when I move my character, will I have to set the frame sequence for those movement methods and for standing still, will I have to create a method that uses a boolean to indicate whether or not the character is moving so that it can be set back to the first frame? Enclosed is the code for my game screen and player sprite. EDIT: I got it working and I realized why there were movement issues when running my midlet in my phone's default J2ME emulator. It seems that it only implements the basic stuff and only implemented the Game API sparingly. That and after reading up more about this issue, it seems that it is not suited for gaming, thus it has a lot of compatibility issues with lots of games. Luckily, the IBM J2ME Midlet launcher FULLY implements J2ME w/o cutting corners and managed to move my sprite across my tile layer just like in the emulator. Granted it lags a little, but a toning down of my graphics should do the trick. my game screen class (update 3/29/06)
package de.enough.polish.example;

import javax.microedition.lcdui.game.*;
import javax.microedition.lcdui.*;
import java.util.*;

public class GameScreen extends GameCanvas implements Runnable, CommandListener{
    static final int MILLIS_PER_TICK = 50;
    private static final int RUN_OFF = 0;
    private Command backCommand = new Command("Back", Command.BACK,1);
    private MenuMidlet midlet;
    private LayerManager layerManager;
    private Thread gameThread;
    private TiledLayer background;
    private int keyPress;
    private int regGameCodes;
    private TheLevels theLevels;
    private Display display;
    private int width;
    private int height;
    private int screenViewWidth;
    private int screenViewHeight;
    private int scnX, scnY;
    private Image cityBackground;
    boolean isPlay;
    private PlayerSprite playerSprite;
    private Sprite backgroundSprite;
    private int currentFrame = 1;
    private static final int MOVE_RATE = 5;
    private static final int END_TILELAYER_BUFFER = 15;
    private static final int OFFSET_LEFT = 30;
    private static final int OFFSET_RIGHT = 120;
    
    public GameScreen(MenuMidlet midlet) throws Exception {
        super(false);
        this.midlet=midlet;
        addCommand(backCommand);
        setCommandListener(this);

        isPlay = true;
        
        theLevels = new TheLevels(screenViewHeight);
        //theLevels.setMap(2);
        background = theLevels.getBackground();
        
        width=getWidth();
        height=getHeight();
        screenViewHeight = width;
        
        scnX=0;
        
        Image playerImage = Image.createImage("/sprite.png");
        playerSprite = new PlayerSprite(playerImage,24,56,width,height);
        playerSprite.startPosition();
        
        
        layerManager = new LayerManager();
        layerManager.append(playerSprite);
        layerManager.append(background);
        //layerManager.append(backgroundSprite);
    }
    public void start() {
        gameThread = new Thread(this);
        gameThread.start();
        try {
            cityBackground = Image.createImage("/citybg.png");
        }
        catch (Exception e){
            
        }
        //#debug
        System.out.print("Game thread running");

    }
    // Stop thread for game loop
    public void stop() {
        gameThread = null;
    }
    
    public void run() {
        Graphics g = getGraphics();
        
        Thread currentThread = Thread.currentThread();
        try{
            while (currentThread == gameThread) {
                long startTime = System.currentTimeMillis();
                if (isShown()) {
                    if (isPlay) {
                        switch(regGameCodes){
                            case UP: playerSprite.moveUp(); break;
                            case DOWN: playerSprite.moveDown(); break;
                            case LEFT: 
                                playerSprite.moveLeft(); 
                                if ((scnX > 0)&& (playerSprite.getX() < (scnX*MOVE_RATE)+OFFSET_LEFT))
                                    scnX--;
                                break;
                            case RIGHT: 
                                playerSprite.moveRight(); 
                                if ((scnX < getWidth()+END_TILELAYER_BUFFER)&&(playerSprite.getX() > (scnX*MOVE_RATE)+OFFSET_RIGHT))
                                    scnX++;
                                break;
                            //case RUN_OFF: playerSprite.setRunOff(); break;
                        }

                        /*switch(keyPress){
                            case KEY_NUM1: playerSprite.moveUpLeft(); break;
                            case KEY_NUM3: playerSprite.moveUpRight(); break;
                            case KEY_NUM7: playerSprite.moveDownLeft(); break;
                            case KEY_NUM9: playerSprite.moveDownRight(); break;
                            //case RUN_OFF: playerSprite.setRunOff(); break;
                        }*/
                        //debug
                        System.out.println("ScnX: "+scnX*5+". "+"PlayerXPosition: "+playerSprite.getX());
                        //debug
                        System.out.println("Current width: "+getWidth()+". "+"Tile width: "+theLevels.getWidth());
                    }
                    drawScreen(g);
                    //render(g);
                }
                long timeTake = System.currentTimeMillis() - startTime;
                if (timeTake < MILLIS_PER_TICK) {
                    synchronized (this) {
                        wait(MILLIS_PER_TICK - timeTake);
                    }
                } else {
                    currentThread.yield();
                }
            }
        } catch(Exception ex){
            
        }
        
    }
    protected void keyPressed(int keyCode){
        super.keyPressed(keyCode);
        regGameCodes=getGameAction(keyCode);
        keyPress=keyCode;
        if ((regGameCodes == UP) || (regGameCodes == DOWN) || (regGameCodes == LEFT) || (regGameCodes == RIGHT) || (keyPress == KEY_NUM1) || (keyPress == KEY_NUM3) || (keyPress == KEY_NUM7) || (keyPress == KEY_NUM9)){
            playerSprite.setFrameSequence(playerSprite.MOVEMENT_SEQUENCE);
        }
        //playerSprite.setFrameSequence(playerSprite.MOVEMENT_SEQUENCE);
    }
  /*protected void keyRepeated(int keyCode){
      super.keyRepeated(keyCode);
      keyPress=keyCode;
  }*/
    protected void keyReleased(int keyCode){
        super.keyReleased(keyCode);
        regGameCodes=0;
        keyPress=0;
        playerSprite.setFrameSequence(null);
        playerSprite.setFrame(0);
    }
    

    public void commandAction(Command c, Displayable d) {
        if (c == backCommand) {
            midlet.mainMenuShow();
        }
    }
    
   
    public void newGame(){
        try{
            theLevels.setMap(1);
        } catch (Exception e){
            //#debug
            System.out.println(e);
        }
        display.setCurrent(this);
        repaint();
    }
    private void drawScreen(Graphics g) {
        //g.setColor(0x00C000);
        
        g.setColor(0xffffff);
        g.fillRect(0, 0, getWidth(), getHeight());
        /*g.setColor(0x37c3fd);
        g.fillRect(0, 12, 176, 150);*/
        g.drawImage(cityBackground, 0, -20, Graphics.TOP | Graphics.LEFT);
        g.setColor(0x0000ff);

        background = theLevels.getBackground();
        
        // display all layers
        //layerManager.paint(g,0,0);
        layerManager.setViewWindow(scnX*MOVE_RATE,30,176,190);
        layerManager.paint(g,0,0);
        
        flushGraphics();
    }
    
}


my player sprite class (update 3/29/06)
package de.enough.polish.example;

import javax.microedition.lcdui.game.*;
import javax.microedition.lcdui.*;

public class PlayerSprite extends Sprite{
    static final int MOVE = 5;
    static final int XMOVE = 5;
    static final int DMOVE = MOVE*100/141;
    private static final int END_BUFFER = 22;
    private Image image;
    private int xPos;
    private int yPos;
    private int frameWidth;
    private int frameHeight;
    private int scnWidth, scnHeight;
    private int frame;
    public static final int[] MOVEMENT_SEQUENCE={1, 2, 3, 4};
    private boolean isRun;
    private int currentFrame = 0;
    private int maxSpriteFrames = 5;
    private int firstWalkingFrame;
    private int standingFrame = 0;
    private TheLevels theLevels;


    /** Creates a new instance of PlayerSprite */
    public PlayerSprite(Image image, int frameWidth, int frameHeight, int scnWidth, int scnHeight) throws Exception {
        super(image, frameWidth, frameHeight);
        defineReferencePixel(frameWidth/2, frameHeight/2);
        this.scnWidth = scnWidth;
        this.scnHeight = scnHeight;
        this.frameWidth = frameWidth;
        this.frameHeight = frameHeight;
        this.isRun = false;
        this.setFrame(0);
    }
  public void startPosition() {
    setPosition(scnWidth/2,scnHeight-85);
    
  }
    //this.setFrameSequence(MOVEMENT_SEQUENCE);
  public void moveLeft() {
      //getXY();
    if (getX() - XMOVE > 0) {
      move(XMOVE * -1,0);
      setTransform(TRANS_MIRROR);
      nextFrame();
      isRun = true;
      System.out.println("Left");
      //debug
      System.out.println("X: "+ MOVE);
    }
  }
  public void moveRight() {
      //getXY();
    if (getX() + XMOVE + END_BUFFER < (scnWidth*6)+96) {
      move(XMOVE,0);
      setTransform(TRANS_NONE);
      nextFrame();
      isRun = true;
      System.out.println("Right");
      //debug
      System.out.println("Y: "+ MOVE);
    }
  }
  public void moveUp() {
      //getXY();
    if (getY() - MOVE > scnHeight-90)
      move(0, MOVE * -1);
      nextFrame();
      isRun = true;
      System.out.println("Up");
  }
  public void moveDown() {
      //getXY();
    if (getY() + MOVE + getHeight() < scnHeight+20)
      move(0,MOVE);
      nextFrame();
      isRun = true;
      System.out.println("Down");
  }
  public void moveUpLeft(){
      //getXY();
    if(xPos-DMOVE>0&&yPos-DMOVE>0)
      move(-DMOVE,-DMOVE);
      setTransform(TRANS_MIRROR);
      nextFrame();
      isRun = true;
  }
  public void moveUpRight(){
      //getXY();
    if(xPos+DMOVE+frameWidth<scnWidth&&yPos-DMOVE>0)
      move(DMOVE,-DMOVE);
      setTransform(TRANS_NONE);
      nextFrame();
      isRun = true;
  }
  public void moveDownLeft(){
     //getXY();
    if(xPos-DMOVE>0&&yPos+DMOVE+frameHeight<scnHeight)
      move(-DMOVE, DMOVE);
      setTransform(TRANS_MIRROR);
      nextFrame();
      isRun = true;
  }
  public void moveDownRight(){
      //getXY();
    if(xPos+DMOVE+frameWidth<scnWidth&&yPos+DMOVE+frameHeight<scnHeight)
      move(DMOVE,DMOVE);
      setTransform(TRANS_NONE);
      nextFrame();
      isRun = true;
  }

  /*public void getXY(){
      xPos=getX();
      yPos=getY();
  }*/
  public int giveX(){
      return xPos;
  }
  public int giveY(){
      return yPos;
  }
  public void setRunOff(){
      if (isRun){
          isRun = false;
          setFrameSequence(null);
          setFrame(0);
      }
  }

}



[Edited by - thelegendofzaku on March 29, 2006 11:05:34 PM]

Share this post


Link to post
Share on other sites
OK, I was able to fix the key pressing issue that I had. Looks like when I called super in my contstructor, it was set on true. After setting it on false, I was able to move my sprite in eight directions in the emulator, but on the real device, it only moved up and down, any takers? Anways, now the other problem I have is trying to juggle the sprite frame calls so that it cycles through a four-frame endless loop while walking and that the contstricts my sprite to my street pavement tile (all you need to know is that the pavement tile is 64x64. I'll update the source code from my first post on this thread.

Share this post


Link to post
Share on other sites
I'll have a go at answering your walking animation question.
If you have 5 frames but the first one (standing still) is never used in the walking animation then you could try something like the following.

When user presses the arrow key (to walk) the player begins walking. When the user stops pressing the arrow key the player stops walking and goes to the standing still image.

So

if (arrow key is pressed)
player.move();
else // no arrow pressed so no movement.
player.standing();

move() {
spriteImage.setFrame(currentFrame++)
if (currentFrame &gt; maxSpriteFrames)
currentFrame = firstWalkingFrame;
}

standing() {
spriteImage.setFrame(standingFrame);
currentFrame = standingFrame;
}




The above is puedocode, but basically whenever the arrow key is pressed the player will just cycle through the walking animation. Whenever the player stops pressing the arrow the player will go back to the standing frame and set the walking animation back to the start (currentFrame = standingFrame).
You should be able to expand the above to work for multiple directions. Just create methods called moveLeft, moveRight etc.

Hopefully this is clear. If not let me know.

Greig

Share this post


Link to post
Share on other sites
Well, I was able to make my sprites animate when moved, and all it took was for me to set the frame sequences accordingly in the keyPressed and keyReleased methods. I have a feeling that it might get complicated when I have to set other sequences for things like punching and kicking frame sequences. Now on to another issue that I'm facing. I was wondering if someone can take a look at my two updated classes. I'm having a hard time trying to keep the scrolling within the dimensions of the tile layers since everytime I move my sprite to the very end of my tile layer, the view window goes beyond the last tile column, exposing the layers underneath it. That and for some reason, the scrolling is not working on my device, but works fine on the emulator. In other words, I can only move my sprite vertically on my phone, but when I try hitting the left or right key presses, it gets stuck and my sprite does not move at all, but still runs through the frame sequence. Also, I need help setting offsets so that the view window moves from a given point from a given direction in the total screen width. For example, let's say that my frame is originally centered in the middle of the screen and that my screen width is 176. I want to set conditions so that it would move the view window backwards if the current x position is above 44 pixels from the beginning of the screen width and that is within the length of the tile layer and to move forward if the current x position is above 132 pixels and it is within the total length of the tile layer. In other words, I want my view window follow the offsetted direction of my Sprite. Can somebody get back to me about this. My first post should have the latest code.

[Edited by - thelegendofzaku on March 8, 2006 11:14:11 AM]

Share this post


Link to post
Share on other sites
I'm gonna give out more info which will help others solve this problem. So my tile layer is 18 tiles (each tile is 64 pixels wide) long, making it 1152. What I wanna do is have the view window move in a direction whenever the sprite is in a current horizontal pixel that is defined, you know like a trigger. In other words, since my current screen width is 176, I want my sprite to move the view window forwards when my sprite's current X position is 132 and to move it backwards when the sprites current X position is 88. Also, the view window must not be able to go beyond the boundaries of the tile layer. Someone please get to me about this.

Share this post


Link to post
Share on other sites
Sorry to bump this but I seriously need someone's help on this please, since I want to get this issue out of the way once and for all. I wanna see if I can use maximum values for moving left so that the screen does not go beyond the beginning of the tile layer and minimum values so that the screen does not go beyond the last tile layer column. The problem that I'm having is in trying to implement these conditions in my sprite class, since at the moment, there is an if statement in my left and right methods in that for example when I move left, it will only move the sprite five number of pixels backwards per paint call if the sprite's current x position plus the rate in which I move my sprite (defined by x which happens to be five) is greater than zero and when I try moving to the right, it will only move my sprite five number of times if my sprites current x position + plus five plus 20 (just so that the screen does not go beyond the tile layer) is greater than the total width of the tile layer, which is 1150. With my current code, I am able to move left and right, however, whenever I reach the end of the tile layer on the right and I then move the opposite direction, the screen scrolls backward from that endpoint without an offset of a few pixels. As a result, when I scroll a little bit backwards and then move forwards again, my screen does not scroll at all. The same behavior occurs when I move my sprite to the beginning of the tile layer, in that the screen moves forward from the very beginning and cuts off my sprite when I move left. In other words, I want to create screen offsets so that my screen only moves to the right when my sprite reaches pixel 125 out of the screen witdh of 176 regardless of where it is on the tile layer; the same goes for only scrolling to the left if it is on the 35 pixel of the screen width. Someone please get back to me about this.

EDIT: Code updated in the first post.

Share this post


Link to post
Share on other sites

This topic is 4284 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this