[Home]Marshmallow/CodeSnippets

Robo Home | Marshmallow | Changes | Preferences | AllPages


How Marshmallow checks if its VirtualBullets has hit or missed

Marshmallow has a very close (to the decimal percentage) relation between virtual bullet hit ratio and real bullet hit ratio. This might or might not be common. Here's the relevant code anyway:

private Point2D enemyLocation;
private Point2D bulletLocation;
private Point2D oldRobotLocation;
private double radius = 20.0;
...
        boolean hasHit() {
            // calculate bulletLocation here
            if (bulletLocation.distance(enemy.location) < radius) {
                active = false;
                return true;
            }
            else {
                return false;
            }
        }

        boolean hasMissed() {
            // calculate bulletLocation here
            if (oldRobotLocation.distance(bulletLocation) > oldRobotLocation.distance(enemy.location)) {
                active = false;
                return true;
            }
            else {
                return false;
            }
        }
I used to calculate a circle (Ellipse2D) around the enemyLocation and check to see if the bulletLocation was contained in that circle, but suddenly realised this way is simpler and achives the exact same results. To calculate the bulletLocation we need: With these we can:
bulletDistance = bulletVelocity * (nowTime - firedTime);
X = oldRobotLocation.getX() + sin(Math.toDegrees(bulletBearing)) * bulletDistance;
Y = oldRobotLocation.getY() + cos(Math.toDegrees(bulletBearing)) * bulletDistance;
bulletLocation.setLocation(X, Y);
Of course some of this should be encapsulated into a generic function. Marshmallow has a robot utilities class with a function like this:
    static void setLocationFromVector(double angle, double length, Point2D sourceLocation, Point2D targetLocation) {
        double X = sourceLocation.getX() + sin(angle) * length;
        double Y = sourceLocation.getY() + cos(angle) * length;
        targetLocation.setLocation(X, Y);
    }
And sin/cos functions like these:
    static double cos(double a) {
        return Math.cos(Math.toRadians(a));
    }

    static double sin(double a) {
        return Math.sin(Math.toRadians(a));
    }
Feel free to use this code. Give me credit if you think I deserve it. -- PEZ

Robo Home | Marshmallow | Changes | Preferences | AllPages
Edit text of this page | View other revisions
Last edited May 17, 2003 1:28 EST by PEZ (diff)
Search: