diff --git a/src/Q4.java b/src/Q4.java index bf68e52fa9c2da3f09efcb19a34b7d3413e86bd8..a55c0beec92d15cdf4c8188e45a1254479d25887 100644 --- a/src/Q4.java +++ b/src/Q4.java @@ -27,6 +27,28 @@ public class Q4 extends AbstractGame { private final Font font = new Font("res/conformable.otf", 24); private static final Point FONT_POSITION = new Point(32, 32); + // Now, we are revising the catch the Ball game so that the player moves toward the ball step by step. In + //this question, you will learn how to set the player's moving direction and how to let the player move + //towards this direction by one step. Let the movement of the player controlled by the Enter key, not + //the arrow keys: + // (0) If the Enter key is pressed (use Input.wasPressed method), do the following: + + // (a) Calculate the direction (xd; yd) pointing from the player to the ball: for (x1; y1) and (x2; y2) being + // the positions of the player and the ball respectively, set: + // xd = (x2-x1) / Math.sqrt(Math.pow(x1-x2, 2) + Math.pow(y1-y2, 2)) + // yd = (y2-y1) / Math.sqrt(Math.pow(x1-x2, 2) + Math.pow(y1-y2, 2)) + private double playerDirectionX = 0, + playerDirectionY = 0; + + /** + * calculate the direction for the player based on the input point w.r.t. player's location + * @param Dest destination for the player to move to + */ + public void setPlayerDirectionTo(Point Dest){ + double Len = new Point(playerX, playerY).distanceTo(Dest); + playerDirectionX = (Dest.x - playerX)/Len; + playerDirectionY = (Dest.y - playerY)/Len; + } public static void main(String[] args) { new Q4().run(); @@ -37,13 +59,20 @@ public class Q4 extends AbstractGame { if (input.wasPressed(Keys.ESCAPE)) { System.out.println("closed"); Window.close(); - } + } else { + // (0) + if (input.wasPressed(Keys.ENTER)) { + // (a) + this.setPlayerDirectionTo(BALL_POSITION); + } - if (new Point(playerX, playerY).distanceTo(BALL_POSITION) <= SCORE_DISTANCE) { - // System.out.println("Great job!"); - font.drawString("Great job!", FONT_POSITION.x, FONT_POSITION.y); + if (new Point(playerX, playerY).distanceTo(BALL_POSITION) <= SCORE_DISTANCE) { + // System.out.println("Great job!"); + font.drawString("Great job!", FONT_POSITION.x, FONT_POSITION.y); + } } + playerImage.draw(playerX, playerY); ballImage.draw(BALL_POSITION.x, BALL_POSITION.y); }