在更新循环中单击鼠标移动播放器

我正在尝试移动我的播放器时,单击鼠标右键。 问题是我的玩家只是站在左上角“摇晃”。 在这里输入图像说明

任何想法?

package game; import java.awt.Color; import java.awt.Graphics; import java.awt.Rectangle; import java.awt.event.MouseEvent; import javax.swing.JLabel; public class Player { private Rectangle playerRec; float x, y; PlayerJLabel playerJLabel; int worldX = 800; int worldY = 600; int targetX, targetY; public Player(int posX, int posY, int size){ playerRec = new Rectangle(posX, posY, size, size); x = posX; y = posY; playerJLabel = new PlayerJLabel(); playerJLabel.setBounds(0, 0, 800, 600); Game.screen.add(playerJLabel); } public void update(float timeSinceLastFrame){ if (Mouse.isMouse(MouseEvent.BUTTON3)) { targetX = Mouse.getX(); targetY = Mouse.getY(); } if ((targetX != 0 && targetX != x) && (targetY != 0 && targetY != y)) { float dx = (float) (targetX-x); float dy = (float) (targetY-y); // normalize float length = (float) Math.sqrt(dx*dx+dy*dy); dx/=length; dy/=length; // add speed x = dx * timeSinceLastFrame * 300; y = dy * timeSinceLastFrame * 300; // Move the player playerRec.x = (int) x; playerRec.y = (int) y; } } private Rectangle getRec(){ return playerRec; } public class PlayerJLabel extends JLabel{ @Override protected void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.RED); g.fillRect(getRec().x, getRec().y, getRec().width, getRec().height); } } } 

编辑:我有一个GameState方法,它调用播放器的update()方法和重绘整个场景的repaint()方法。

GameState更新方法:

 @Override public void update(float lastFrame) { player.update(lastFrame); } 

游戏重绘方法:

 public void repaint() { // screen is a JFrame Object screen.repaint(); } Main class package game; public class Main { public static void main(String[] args) { Game game = new Game("Mein erstes Spiel", 800, 600); long lastFrame = System.nanoTime(); while(game.isRunning()) { long thisFrame = System.nanoTime(); float timeSinceLastFrame = ((float)(thisFrame-lastFrame))/100000f; lastFrame=thisFrame; game.nextState(); game.update(timeSinceLastFrame); game.repaint(); } } } 

更新2:

我更新了我的代码:

  // Move the player x = playerRec.x += (int) (dx * timeSinceLastFrame * 500); y = playerRec.y += (int) (dy * timeSinceLastFrame * 500); 

我的播放器正在移动,但速度不一样,速度也不是很平滑: http : //screencast.com/t/pv5M9Un4QhFR

我知道。

  // add speed x = dx * timeSinceLastFrame * 300; y = dy * timeSinceLastFrame * 300; // Move the player playerRec.x = (int) x; playerRec.y = (int) y 

实际上是一样的说法

  // Move the player playerRec.x = (int) (dx * timeSinceLastFrame * 300); playerRec.y = (int) (dy * timeSinceLastFrame * 300); 

你可能会想做:

  // Move the player playerRec.x += (int) (dx * timeSinceLastFrame * 300); playerRec.y += (int) (dy * timeSinceLastFrame * 300); 

你需要+ =,不= =。

总是会发生在我身上。