# 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;
...
boolean hasHit() {
// calculate bulletLocation here
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:
• bulletBearing
• bulletVelocity
• firedTime
• nowTime
• oldRobotLocation
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) {