Game Development Reference
In-Depth Information
float y = MathUtils.random(5.0f, 15.0f);
float rotation = MathUtils.random(0.0f, 360.0f)
* MathUtils.degreesToRadians;
float carrotScale = MathUtils.random(0.5f, 1.5f);
carrot.scale.set(carrotScale, carrotScale);
// create box2d body for carrot with start position
// and angle of rotation
BodyDef bodyDef = new BodyDef();
bodyDef.position.set(pos);
bodyDef.position.add(x, y);
bodyDef.angle = rotation;
Body body = b2world.createBody(bodyDef);
body.setType(BodyType.DynamicBody);
carrot.body = body;
// create rectangular shape for carrot to allow
// interactions (collisions) with other objects
PolygonShape polygonShape = new PolygonShape();
float halfWidth = carrot.bounds.width / 2.0f * carrotScale;
float halfHeight = carrot.bounds.height /2.0f * carrotScale;
polygonShape.setAsBox(halfWidth * carrotShapeScale,
halfHeight * carrotShapeScale);
// set physics attributes
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape = polygonShape;
fixtureDef.density = 50;
fixtureDef.restitution = 0.5f;
fixtureDef.friction = 0.5f;
body.createFixture(fixtureDef);
polygonShape.dispose();
// finally, add new carrot to list for updating/rendering
level.carrots.add(carrot);
}
}
The spawnCarrots() method contains the logic to create a variable number
( numCarrots ) of the new carrot game objects at a specific location ( pos ) in the game
world. Inside the loop, a new carrot game object is created for which random values
are calculated for the starting position ( x , y ), angle of rotation ( rotation ), and scale
( carrotScale ). The location that is passed in the pos variable is used as the center
spawn point. The third parameter, radius , is used to distribute the carrots around
the center spawn point of the horizontal starting position. The vertical starting
position is randomly chosen in the range between 5 and 15 to ensure that the carrots
will always spawn outside the game camera's view.
 
Search WWH ::




Custom Search