Coverage Summary for Class: PlayerController (com.mygdx.game.Components)
| Class | Class, % | Method, % | Line, % |
|---|---|---|---|
| PlayerController | 100% (1/1) | 50% (2/4) | 17.1% (6/35) |
1 package com.mygdx.game.Components; 2 3 import com.badlogic.gdx.Gdx; 4 import com.badlogic.gdx.Input; 5 import com.badlogic.gdx.math.Vector2; 6 import com.badlogic.gdx.math.Vector3; 7 import com.mygdx.game.Entitys.Player; 8 import com.mygdx.game.Entitys.Ship; 9 import com.mygdx.game.Managers.RenderingManager; 10 11 import static com.mygdx.utils.Constants.HALF_DIMENSIONS; 12 13 /** 14 * Responsible for the keyboard/mouse control of the player 15 */ 16 public class PlayerController extends Component { 17 private Player player; 18 private float speed; 19 20 21 public PlayerController() { 22 super(); 23 type = ComponentType.PlayerController; 24 setRequirements(ComponentType.RigidBody); 25 } 26 27 /** 28 * @param player the parent 29 * @param speed speed 30 */ 31 public PlayerController(Player player, float speed) { 32 this(); 33 this.player = player; 34 this.speed = speed; 35 36 } 37 38 /** 39 * Reads keyboard and mouse inputs, moving and shooting as required. 40 */ 41 @Override 42 public void update() { 43 super.update(); 44 final float s = speed; 45 46 Vector2 dir = getDirFromWASDInput(); 47 ((Ship) parent).setShipDirection(dir); 48 dir.scl(s); 49 50 RigidBody rb = parent.getComponent(RigidBody.class); 51 rb.setVelocity(dir); 52 53 RenderingManager.getCamera().position.set(new Vector3(player.getPosition(), 0.0f)); 54 RenderingManager.getCamera().update(); 55 56 if (Gdx.input.isButtonJustPressed(Input.Buttons.LEFT)) { 57 int x = Gdx.input.getX(); 58 int y = Gdx.input.getY(); 59 60 // in range 0 to VIEWPORT 0, 0 bottom left 61 Vector2 delta = new Vector2(x, y); 62 delta.sub(HALF_DIMENSIONS); // center 0, 0 63 delta.nor(); 64 delta.y *= -1; 65 // unit dir to fire 66 ((Ship) parent).shoot(delta); 67 } 68 69 if (Gdx.input.isKeyJustPressed(Input.Keys.SPACE)) { 70 // unit dir to fire 71 ((Ship) parent).shoot(); 72 } 73 74 } 75 76 /** 77 * Converts WASD or arrows to direction of travel 78 * 79 * @return -1 <= (x, y) <= 1 80 */ 81 private Vector2 getDirFromWASDInput() { 82 Vector2 dir = new Vector2(0, 0); 83 84 if (Gdx.input.isKeyPressed(Input.Keys.W) || Gdx.input.isKeyPressed(Input.Keys.DPAD_UP)) { 85 dir.y += 1; 86 } 87 88 if (Gdx.input.isKeyPressed(Input.Keys.S) || Gdx.input.isKeyPressed(Input.Keys.DPAD_DOWN)) { 89 dir.y -= 1; 90 } 91 92 if (Gdx.input.isKeyPressed(Input.Keys.A) || Gdx.input.isKeyPressed(Input.Keys.DPAD_LEFT)) { 93 dir.x -= 1; 94 } 95 96 if (Gdx.input.isKeyPressed(Input.Keys.D) || Gdx.input.isKeyPressed(Input.Keys.DPAD_RIGHT)) { 97 dir.x += 1; 98 } 99 return dir; 100 } 101 102 103 }