处理我的精灵不会移动

时间:2015-01-13 20:06:24

标签: java processing

你可以帮助我让我的精灵左右走路吗?我只是看不出问题出在哪里。 我花了3个小时查看代码,但我不知道我在哪里弄错了......

class Player {

  PImage playerr;
  PVector position;
  PVector velocity;
  float direction;
  float speed;
  float ground = 600;
  float left;
  float right;

  Player()
  {
    playerr = loadImage("sir1.png");
    position = new PVector(400, ground);
    direction = 1;
    speed = 4;
    velocity = new PVector(0, 0);
  }



void update()
{
    velocity.x = speed * (left + right);
    PVector nextPosition = new PVector(position.x, position.y);
    pushMatrix();
    translate(position.x, position.y);
    scale(direction, 1);
    image(playerr, 0, 0);
    popMatrix();
}

void keyPressed()
{
  if (key == RIGHT)
  {
    right += 5;
    direction = -1;
  }
  if (key == LEFT)
  {
    left -= 5;
    direction = 1;
  }
}

void keyReleased()
{
  if (key == RIGHT)
  {
    right = 0;
  }
  if (key == LEFT)
  {
    left = 0;
  }
 }

}

那是主程序

int stage;
PFont startfont;
PFont normalfont;
PImage gameplan;

boolean[] keys = new boolean[526];

ArrayList knight;

void setup()
{
  size(800,800);
  frameRate(60);
  stage = 1;
  knight = new ArrayList();
  smooth();
}

void draw()
{
  switch(stage)
  {
    case 1:
      splash();
      break;
    case 2:
     game();
      break;
    case 3:
      help();
      break;
    case 4:
      help();
      break;
   }

}

void game()
{
  gameplan = loadImage("background.png");
  gameplan.resize(800,800);
  background(gameplan);
  knight.add(new Player());
  for(int i = 0; i <knight.size(); i++)
  {
     Player p = (Player) knight.get(i); 
     p.update();

  }


}

void splash()
{
    background(0);
    startfont = createFont("start.ttf",40);
    normalfont = createFont("start.ttf",25);
    textFont(startfont);
    text("Zombie Destruction",100,300);
    textFont(normalfont);
    text("Press Space to start",200,400);
    text("Press H for help",250,500);
    if(keyPressed)
    {
      if(key == 'h' || key == 'H')
      {
        stage = 4;
      }
    }
    if(keyPressed)
    {
      if(key == ' ')
      {
        stage = 2;
      }
    }
}
void help()
{
    background(0);
    startfont = createFont("start.ttf",40);
    normalfont = createFont("start.ttf",25);
    textFont(normalfont);
    text("Zombie Destruction",100,300);
    textFont(normalfont);
    text("Press Space to go back",200,400);
    if(keyPressed)
    {
      if(key == 'b')
      {
        stage = 1;
      }
      else
      {
        stage = 4;
      }
    }
}

1 个答案:

答案 0 :(得分:1)

我认为问题出在Player类的update()方法中。看起来您正在计算更新的速度,但是您永远不会将该速度添加到玩家的位置。一个简单的

position.x += velocity.x;

应该这样做。