Gate.java
/*
* Copyright © 2011 Nokia Corporation. All rights reserved.
* Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation.
* Oracle and Java are trademarks or registered trademarks of Oracle and/or its
* affiliates. Other product and company names mentioned herein may be trademarks
* or trade names of their respective owners.
* See LICENSE.TXT for license information.
*/
package com.nokia.example.racer.views.components;
import javax.microedition.lcdui.Graphics;
public class Gate {
private static final int LIMIT = 10;
private int start_x;
private int start_y;
private int end_x;
private int end_y;
private int point_x = 0;
private int point_y = 0;
private int temp_x = 0;
private int temp_y = 0;
public static boolean debug = false; //sets gate debug on. Draws all the calculations.
public Gate(int start_x, int start_y, int end_x, int end_y) {
this.start_x = start_x;
this.start_y = start_y;
this.end_x = end_x;
this.end_y = end_y;
}
/**
* If the center of the car is enough near the gate we return true otherwise false.
* You can look the mathematical algorithm from: http://local.wasp.uwa.edu.au/~pbourke/geometry/pointline/
* @param x
* @param y
* @return true if point is near otherwise false
*/
public boolean isPointNear(double x, double y) {
point_x = (int)x;
point_y = (int)y;
double line_x = 0;
double line_y = 0;
boolean ret = false;
double xdiff = end_x - start_x;
double ydiff = end_y - start_y;
double u = ((x - start_x)*xdiff + (y - start_y)*ydiff) /(xdiff*xdiff + ydiff*ydiff);
if(u < 0) {
line_x = start_x;
line_y = start_y;
}else if(u > 1) {
line_x = end_x;
line_y = end_y;
}else {
line_x = (start_x + u*xdiff);
line_y = (start_y + u*ydiff);
}
temp_x = (int) line_x;
temp_y = (int) line_y;
double xdiff2 = line_x - x;
double ydiff2 = line_y - y;
double length = Math.sqrt((xdiff2*xdiff2 + ydiff2*ydiff2));
if(length <= LIMIT)
ret = true;
return ret;
}
public void render(Graphics g) {
g.setColor(0xFF0000);
g.drawLine(start_x, start_y, end_x, end_y);
if(debug) {
g.setColor(0x0000FF);
g.drawLine(point_x, point_y, temp_x, temp_y);
}
}
}