Package pong.server.model

Source Code of pong.server.model.CollisionDetector

/**
*
*/
package pong.server.model;

import java.awt.geom.Ellipse2D;
import java.awt.geom.Rectangle2D;

import pong.common.GlobalSettings;
import pong.common.Position;
import pong.server.ServerSettings;

/**
* A collision detector that will check for collisions with top and bottom walls and with rackets.
*
* @author Lorenzo
*
*/
public class CollisionDetector implements CollisionDetectorInterface {

  @Override
  public void handleCollisions(final Player[] players, final Ball ball) {
    final Float ballX = ball.getPosition().getX();
    Float ballY = ball.getPosition().getY();
    // check collision with walls
    // collision with top wall
    if (ballY < 0) {
      ball.setAngularCoefficient(-ball.getAngularCoefficient());
      ballY = 0f;
    }
    // collision with bottom wall
    if (ballY > GlobalSettings.FIELD_HEIGHT - GlobalSettings.BALL_DIAMETER) {
      ball.setAngularCoefficient(-ball.getAngularCoefficient());
      ballY = (float) (GlobalSettings.FIELD_HEIGHT - GlobalSettings.BALL_DIAMETER);
    }
    // check collision with rackets
    final Ellipse2D.Float ball2D = new Ellipse2D.Float(ballX, ballY,
        GlobalSettings.BALL_DIAMETER, GlobalSettings.BALL_DIAMETER);
    for (int i = 0; i < 2; i++) {
      final Float playerX = players[i].getPosition().getX();
      final Float playerY = players[i].getPosition().getY();
      if (((i == 0 && ball.getDirection() == Ball.Direction.RIGHT_TO_LEFT) || (i == 1 && ball
          .getDirection() == Ball.Direction.LEFT_TO_RIGHT))
          && ball2D.intersects(new Rectangle2D.Float(playerX, playerY,
              GlobalSettings.RACKET_WIDTH, GlobalSettings.RACKET_HEIGHT))) {
        if (i == 0) { // ball is moving right to left
          ball.setDirection(Ball.Direction.LEFT_TO_RIGHT);
        } else {
          ball.setDirection(Ball.Direction.RIGHT_TO_LEFT);
        }
        // randomly change the angular coefficient
        ball.setAngularCoefficient((float) (Math.random() * ServerSettings.MAX_ANGULAR_COEFFICIENT * 2 - ServerSettings.MAX_ANGULAR_COEFFICIENT));
      }
    }
    ball.setPosition(new Position(ballX, ballY));
  }

}
TOP

Related Classes of pong.server.model.CollisionDetector

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.