Skip to content
Snippets Groups Projects
Commit 8982a525 authored by yangxvlin's avatar yangxvlin
Browse files

finish Q4a

parent b9c75531
Branches
No related tags found
No related merge requests found
...@@ -27,6 +27,28 @@ public class Q4 extends AbstractGame { ...@@ -27,6 +27,28 @@ public class Q4 extends AbstractGame {
private final Font font = new Font("res/conformable.otf", 24); private final Font font = new Font("res/conformable.otf", 24);
private static final Point FONT_POSITION = new Point(32, 32); 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) { public static void main(String[] args) {
new Q4().run(); new Q4().run();
...@@ -37,12 +59,19 @@ public class Q4 extends AbstractGame { ...@@ -37,12 +59,19 @@ public class Q4 extends AbstractGame {
if (input.wasPressed(Keys.ESCAPE)) { if (input.wasPressed(Keys.ESCAPE)) {
System.out.println("closed"); System.out.println("closed");
Window.close(); Window.close();
} else {
// (0)
if (input.wasPressed(Keys.ENTER)) {
// (a)
this.setPlayerDirectionTo(BALL_POSITION);
} }
if (new Point(playerX, playerY).distanceTo(BALL_POSITION) <= SCORE_DISTANCE) { if (new Point(playerX, playerY).distanceTo(BALL_POSITION) <= SCORE_DISTANCE) {
// System.out.println("Great job!"); // System.out.println("Great job!");
font.drawString("Great job!", FONT_POSITION.x, FONT_POSITION.y); font.drawString("Great job!", FONT_POSITION.x, FONT_POSITION.y);
} }
}
playerImage.draw(playerX, playerY); playerImage.draw(playerX, playerY);
ballImage.draw(BALL_POSITION.x, BALL_POSITION.y); ballImage.draw(BALL_POSITION.x, BALL_POSITION.y);
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment