UMUC Asia - CMSC325 - Game Design and Development
をテンプレートにして作成
[
トップ
] [
新規
|
一覧
|
単語検索
|
最終更新
|
ヘルプ
]
開始行:
#contents
** Week 1 Participation Topic: Personal Experience [#i5e0...
- Question
Please reply to this topic with your background in gaming.
Specify your first experience of gaming and the game syst...
What game system do you currently own/use, including cons...
What is your favorite game and game type? Why do you like...
Lastly, please outline your future career plan in gaming ...
- Answer
''Specify your first experience of gaming and the game sy...
My first game console I ever used was Nintendo Family Com...
Also my first mobile device I used was Game Boy, and what...
''What game system do you currently own/use, including co...
Game systems I currently own are as follows.
Consoles: PlayStation, PlayStation 2~
Mobile devices: Game Boy Light, Android Phone, iPhone 5~
Mac: iBook G4, Macbook
''What is your favorite game and game type? Why do you li...
Role-playing Games (RPGs) are the most favorite because i...
In addition to RPGs, I also like simulation games. I ofte...
''Lastly, please outline your future career plan in gamin...
In my future, I am interested in working for creating soc...
** Week 1 Homework 1 [#j0cada60]
- Question
Your task for this first homework assignment is to instal...
What to submit:
-- All the source code for your game.
-- A compiled JAR or executable file.
-- A text file briefly describing how to run and play you...
All of the above should be attached to your assignment as...
- Answer
- CoinFlipTest.java
import java.util.*;
import javax.swing.*;
public class CoinFlipTest {
public static void main(String[] args) {
int select, rand, result;
String selectvalues[] = {"Heads", "Tails"};
String coinSides=null, userGuess=null;
/** Instantiate an array list for storing outcomes. **/
ArrayList<Integer> outcomes = new ArrayList<Integer>();
for (int i=0; i<100; i++) { // Determine the number of...
/** Flip the coin, and then it comes up heads or tail...
rand = generateRandomValue();
if (rand == 0) {
coinSides = "Heads";
} else {
coinSides = "Tails";
}
/** User selection **/
int j = i + 1;
select = JOptionPane.showOptionDialog(null,
"Choose Heads or Tails. " + "(Number of times: " + ...
"Your Guess",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
selectvalues,
selectvalues[0]);
// if user click on the close button, break out of th...
if (select == JOptionPane.CLOSED_OPTION) {
break;
}
/** Determine if user guess is right or wrong. **/
if (rand == select) {
userGuess = "right";
outcomes.add(0); // if right => 0
} else {
userGuess = "wrong";
outcomes.add(1); // if wrong => 1
}
/** Display a result. **/
JOptionPane.showMessageDialog(null,
"The result is " + coinSides + "! " + "Your guess i...
"Result",
JOptionPane.INFORMATION_MESSAGE);
}
/** Display the odds **/
JOptionPane.showMessageDialog(null,
"Your odds of getting the right guess are " + calcul...
"Your Odds",
JOptionPane.INFORMATION_MESSAGE);
}
/** Generate a random value for flip of a coin. **/
private static int generateRandomValue() {
int r = (int) (Math.random()*2);
return r;
}
/** Calculate user odds. **/
private static float calculateOdds(ArrayList<Integer> l...
int numOfRightAnswers=0, numOfWrongAnswers=0;
Iterator it = list.iterator();
while(it.hasNext()) {
Integer e = (Integer) (it.next());
if (e == 0) {
numOfRightAnswers++;
} else {
numOfWrongAnswers++;
}
}
// odds = the number of desirable outcomes/the number ...
return (float) numOfRightAnswers/numOfWrongAnswers;
}
}
** Week 2 Participation Topic: Storytelling in Games [#dd...
- Question
Pick a story-driven game that you have recently played. S...
Describe what the game was, what captivated you about the...
If you cannot think of any games for your story-telling, ...
- Answer
One of the best story-driven games that I ever played was...
The story is set in 1964 after the Cuban Missile Crisis i...
In addition to its splendid story, its 3D depiction makes...
** Week 2 Homework 2 [#rdf9b39b]
- Question
Within 500 words, describe the social implications of gam...
As with all written assignments, please review your paper...
- Answer
#ref(CMSC325_Homework2.pdf)
** Week 3 Project 1: Questions and Comments [#a32901fe]
- My Question
I am wondering which I should choose Java or C++ as my la...
Hopefully I would like to use OpenGL with C++ because I t...
Can I submit only header files and source codes? Or, do I...
What do you recommend?
- Professor's answer
I would recommend you to use JMonkey 3d engine, which is ...
Just go over the tutorials to get started.
** Week 3 Project 1 [#f4c3448b]
- Question
You will use an existing game engine and map to modify an...
The level you create must be unique, realistic and playab...
''The following components and design criteria should be ...
-- Any code borrowed from other sources and sites must be...
-- A comprehensive test suite should be used and document...
''Deliverables include:''
-- All source code
-- Compile and run instructions
-- Test suite data and description along with output resu...
- BouncingBallsMain.java
import com.jme3.app.SimpleApplication;
import com.jme3.bullet.BulletAppState;
import com.jme3.bullet.control.RigidBodyControl;
import com.jme3.collision.CollisionResult;
import com.jme3.collision.CollisionResults;
import com.jme3.font.BitmapText;
import com.jme3.input.MouseInput;
import com.jme3.input.controls.ActionListener;
import com.jme3.input.controls.MouseButtonTrigger;
import com.jme3.material.Material;
import com.jme3.material.RenderState.BlendMode;
import com.jme3.math.ColorRGBA;
import com.jme3.math.Ray;
import com.jme3.math.Vector3f;
import com.jme3.renderer.queue.RenderQueue;
import com.jme3.scene.Geometry;
import com.jme3.scene.Node;
import com.jme3.scene.shape.Box;
import com.jme3.scene.shape.Sphere;
import java.util.ArrayList;
/**
* @author yujishimojo
*/
public class BouncingBallsMain extends SimpleApplication {
public static void main(String args[]) {
BouncingBallsMain app = new BouncingBallsMain();
app.start();
}
/** Prepare the Physics Application State (jBullet) */
private BulletAppState bulletAppState;
/** Prepare Materials */
Material ball_mat, floor_mat, red_wall_mat, blue_wall_...
green_wall_mat, yellow_wall_mat;
/** Prepare geometries and physical nodes for walls an...
private RigidBodyControl ball_phy, floor_phy, red_w...
blue_wall_phy, green_wall_...
private static final Sphere sphere;
private static final Box floor, red_wall, blue_wall...
private static Node shootables;
private static Geometry ball_geo, floor_geo, red_wall_...
green_wall_geo, yellow_wall_ge...
private static ArrayList list1, list2;
static {
/** Initialize the ball geometry */
sphere = new Sphere(32, 32, 0.4f, true, false);
/** Initialize the floor geometry */
floor = new Box(Vector3f.ZERO, 5f, 0.1f, 5f);
/** Initialize the walls geometry */
red_wall = new Box(Vector3f.ZERO, 5f, 5f, 0.1f);
blue_wall = new Box(Vector3f.ZERO, 5f, 5f, 0.1f);
green_wall = new Box(Vector3f.ZERO, 0.1f, 5f, 5f);
yellow_wall = new Box(Vector3f.ZERO, 0.1f, 5f, 5f);
list1 = new ArrayList();
list2 = new ArrayList();
}
@Override
public void simpleInitApp() {
/** Set up Physics Game */
bulletAppState = new BulletAppState();
stateManager.attach(bulletAppState);
// This array is used to decide camera location
float[] array = generateRandomLocation();
/** Configure cam to look at scene */
// Cam location and direction will be selected rando...
cam.setLocation(new Vector3f(array[0], 20f, array[1]...
cam.lookAt(new Vector3f(array[2], 10, array[3]), Vec...
/** Add InputManager action: Left click triggers sho...
inputManager.addMapping("shoot",
new MouseButtonTrigger(MouseInput.BUTTON_LEF...
inputManager.addListener(actionListener, "shoot");
/** Initialize the scene, materials, and physics spa...
initMaterials();
initFloor();
initRedWall();
initBlueWall();
initGreenWall();
initYellowWall();
initCrossHairs();
/** create a floor and four walls to shoot at: */
shootables = new Node("Shootables");
rootNode.attachChild(shootables);
shootables.attachChild(floor_geo);
shootables.attachChild(red_wall_geo);
shootables.attachChild(blue_wall_geo);
shootables.attachChild(green_wall_geo);
shootables.attachChild(yellow_wall_geo);
}
/**
* Every time the shoot action is triggered, a new bal...
* The ball is set up to fly from the camera position ...
*/
private ActionListener actionListener = new ActionList...
public void onAction(String name, boolean keyPressed...
initCrossHairs();
if (name.equals("shoot") && !keyPressed) {
makeBall();
// Reset results list.
CollisionResults results = new CollisionResults();
// Aim the ray from cam loc to cam direction.
Ray ray = new Ray(cam.getLocation(), cam.getDire...
// Collect intersections between Ray and Shootab...
shootables.collideWith(ray, results);
// Print the results
for (int i = 0; i < results.size(); i++) {
float dist = results.getCollision(i).getDistan...
Vector3f pt = results.getCollision(i).getConta...
String hit = results.getCollision(i).getGeomet...
// Display a position of a shpere on collision
// For each hit, we know distance, impact poin...
guiNode.detachAllChildren();
guiFont = assetManager.loadFont("Interface/Fon...
BitmapText text = new BitmapText(guiFont, fals...
text.setSize(guiFont.getCharSet().getRenderedS...
text.setText("Ball hits " + hit + " at " + pt);
text.setLocalTranslation(250, text.getLineHeig...
guiNode.attachChild(text);
// Store 3D vector positions to an array list ...
list1.add(pt);
System.out.println("(x, y, z) = " + list1);
}
if (results.size() > 0) {
CollisionResult closest = results.getClosest...
ball_geo.setLocalTranslation(closest.getCont...
rootNode.attachChild(ball_geo);
} else {
rootNode.detachChild(ball_geo);
}
}
}
};
/** Initialize the materials used in this scene. */
public void initMaterials() {
ball_mat = new Material(assetManager, "Common/MatDef...
ball_mat.setColor("Color", new ColorRGBA(0.4f,0,0.2f...
floor_mat = new Material(assetManager, "Common/MatDe...
floor_mat.setColor("Color", new ColorRGBA(0.6f,0.3f,...
//floor_mat.getAdditionalRenderState().setBlendMode(...
red_wall_mat = new Material(assetManager, "Common/Ma...
red_wall_mat.setColor("Color", new ColorRGBA(0.5f,0f...
//red_wall_mat.getAdditionalRenderState().setBlendMo...
blue_wall_mat = new Material(assetManager, "Common/M...
blue_wall_mat.setColor("Color", new ColorRGBA(0f,0f,...
//blue_wall_mat.getAdditionalRenderState().setBlendM...
green_wall_mat = new Material(assetManager, "Common/...
green_wall_mat.setColor("Color", new ColorRGBA(0f,0....
//green_wall_mat.getAdditionalRenderState().setBlend...
yellow_wall_mat = new Material(assetManager, "Common...
yellow_wall_mat.setColor("Color", new ColorRGBA(0.5f...
//yellow_wall_mat.getAdditionalRenderState().setBlen...
}
/** Make a solid floor. */
public void initFloor() {
floor_geo = new Geometry("floor", floor);
floor_geo.setMaterial(floor_mat);
//make the floor translucent
floor_geo.setQueueBucket(RenderQueue.Bucket.Transluc...
floor_geo.setLocalTranslation(0, 1, 0);
this.rootNode.attachChild(floor_geo);
/* Make the floor physical with mass 0.0f! */
floor_phy = new RigidBodyControl(0.0f);
floor_geo.addControl(floor_phy);
bulletAppState.getPhysicsSpace().add(floor_phy);
}
/** Make solid walls. */
public void initRedWall() {
red_wall_geo = new Geometry("red wall", red_wall);
red_wall_geo.setMaterial(red_wall_mat);
//make the wall translucent
red_wall_geo.setQueueBucket(RenderQueue.Bucket.Trans...
red_wall_geo.setLocalTranslation(0, 5.9f, 5.1f);
this.rootNode.attachChild(red_wall_geo);
/* Make the wall physical with mass 0.0f! */
red_wall_phy = new RigidBodyControl(0.0f);
red_wall_geo.addControl(red_wall_phy);
bulletAppState.getPhysicsSpace().add(red_wall_phy);
}
public void initBlueWall() {
blue_wall_geo = new Geometry("blue wall", blue_wall);
blue_wall_geo.setMaterial(blue_wall_mat);
//make the wall translucent
blue_wall_geo.setQueueBucket(RenderQueue.Bucket.Tran...
blue_wall_geo.setLocalTranslation(0, 5.9f, -5.1f);
this.rootNode.attachChild(blue_wall_geo);
blue_wall_phy = new RigidBodyControl(0.0f);
blue_wall_geo.addControl(blue_wall_phy);
bulletAppState.getPhysicsSpace().add(blue_wall_phy);
}
public void initGreenWall() {
green_wall_geo = new Geometry("green wall", green_wa...
green_wall_geo.setMaterial(green_wall_mat);
//make the wall translucent
green_wall_geo.setQueueBucket(RenderQueue.Bucket.Tra...
green_wall_geo.setLocalTranslation(-5.1f, 5.9f, 0);
this.rootNode.attachChild(green_wall_geo);
green_wall_phy = new RigidBodyControl(0.0f);
green_wall_geo.addControl(green_wall_phy);
bulletAppState.getPhysicsSpace().add(green_wall_phy);
}
public void initYellowWall() {
yellow_wall_geo = new Geometry("yellow wall", yellow...
yellow_wall_geo.setMaterial(yellow_wall_mat);
//make the wall translucent
yellow_wall_geo.setQueueBucket(RenderQueue.Bucket.Tr...
yellow_wall_geo.setLocalTranslation(5.1f, 5.9f, 0);
this.rootNode.attachChild(yellow_wall_geo);
yellow_wall_phy = new RigidBodyControl(0.0f);
yellow_wall_geo.addControl(yellow_wall_phy);
bulletAppState.getPhysicsSpace().add(yellow_wall_phy);
}
/** This method creates one individual physical ball.
* The ball is accelerated and flies
* from the camera position in the camera direction.*/
public void makeBall() {
/** Create a ball geometry. */
ball_geo = new Geometry("ball", sphere);
ball_geo.setMaterial(ball_mat);
shootables.attachChild(ball_geo);
/** Position the ball */
ball_geo.setLocalTranslation(cam.getLocation());
/** Make the ball physcial with a mass > 0.0f */
ball_phy = new RigidBodyControl(1f);
/** Add physical ball to physics space. */
ball_geo.addControl(ball_phy);
bulletAppState.getPhysicsSpace().add(ball_phy);
/** Accelerate the physcial ball to shoot it. */
int velocity = generateRandomVelocity();
ball_phy.setLinearVelocity(cam.getDirection().mult(v...
// Store linear velocities to an array list and show...
list2.add(velocity);
System.out.println("Velocity is " + list2);
/** Set gravity on y-axis. */
ball_phy.setGravity(new Vector3f(0, -5, 0));
}
/** Generate a random velocity from 20 to 80. **/
private int generateRandomVelocity() {
int v = (int) Math.ceil(Math.random()*61)+20;
return v;
}
/** Generate a random camera location between 4. **/
private float[] generateRandomLocation() {
float[] a0 = {5f, 10f, 1f, -1f};
float[] a1 = {10f, -10f, -1f, -1f};
float[] a2 = {-5f, -10f, -1f, 1f};
float[] a3 = {-10f, 5f, 1f, 1f};
int n = (int) Math.floor(Math.random()*4);
switch (n) {
case 0: return a0;
case 1: return a1;
case 2: return a2;
case 3: return a3;
default: return a0;
}
}
/** A plus sign used as crosshairs to help the playe...
protected void initCrossHairs() {
guiNode.detachAllChildren();
guiFont = assetManager.loadFont("Interface/Fonts...
BitmapText ch = new BitmapText(guiFont, false);
ch.setSize(guiFont.getCharSet().getRenderedSize(...
ch.setText("+"); // fake crosshairs :)
ch.setLocalTranslation( // center
settings.getWidth() / 2 - guiFont.getCharSet...
settings.getHeight() / 2 + ch.getLineHeight(...
guiNode.attachChild(ch);
}
}
- [[YouTube Video:https://www.youtube.com/watch?v=vZqhPRf...
** Week 4 Participation Topic: Painting with Triangles [#...
- Question
Since the advent of polygons to draw game objects and mov...
- Answer
Metal Gear Solid series are definitely suited for 3D poly...
- Respond to Joel Braun
I agree with the point that the positioning would be easi...
In fighting games, it is important for users to be able t...
- Respond to Xuefen Li
I agree that Super Mario Bros. is a successful example to...
I think such migration of this kind of game is quite a ha...
** Week 4 Homework 3 [#rd4e0ea7]
- Question
The conference discussion this week will have you looking...
As with all written assignments, please review your paper...
- Answer
#ref(CMSC325_Homework3.pdf)
** Week 5 Participation Topic: Acting Out [#fde4fa05]
- Question
When you think about artificial intelligence, you might i...
This week, I would like everyone to think about and descr...
- Answer
An example of non-traditional AI based game I ever played...
You run your own pro soccer club by making training progr...
Sorry! I could find the only Japanese Web site as below.~
http://www.sakatsuku.com/history/06/
** Week 5 Homework 4 [#z6e2444c]
- Question
Especially with online multiplayer games, companies are h...
As with all written assignments, please review your paper...
- Answer
#ref(CMSC325_Homework4.pdf)
** Week 6 Finding Your Own Path [#cea499f4]
- Question
As you should all have realized by now, designing and mak...
This week, I want to know what you had to go searching fo...
- Answer
I created both PR1 and PR2 by using jMonkeyEngine for the...
http://jmonkeyengine.org/wiki/doku.php/jme3
Sometimes, I can hardly understand of exact behavior and ...
http://www.jmonkeyengine.com/doc/
Because jME org offers a lot of materials, I can find out...
** Week 6 Project 2 [#cd8eb041]
- Question
Create a Java or C# application that simulates a minimum ...
You should submit your completed application Java source ...
''Deliverables include:''
-- All source code
-- Compile and run instructions
-- Test suite data and description along with output resu...
- BouncingBallsMain2.java
import com.jme3.app.SimpleApplication;
import com.jme3.bullet.BulletAppState;
import com.jme3.bullet.collision.PhysicsCollisionEvent;
import com.jme3.bullet.collision.PhysicsCollisionListener;
import com.jme3.bullet.control.RigidBodyControl;
import com.jme3.collision.CollisionResults;
import com.jme3.font.BitmapText;
import com.jme3.input.KeyInput;
import com.jme3.input.controls.ActionListener;
import com.jme3.input.controls.KeyTrigger;
import com.jme3.material.Material;
import com.jme3.material.RenderState.BlendMode;
import com.jme3.math.ColorRGBA;
import com.jme3.math.Ray;
import com.jme3.math.Vector2f;
import com.jme3.math.Vector3f;
import com.jme3.renderer.queue.RenderQueue.Bucket;
import com.jme3.scene.Geometry;
import com.jme3.scene.shape.Box;
import com.jme3.scene.shape.Sphere;
import java.util.Random;
/**
* @author yujishimojo
*/
public class BouncingBallsMain2 extends SimpleApplicatio...
public static BouncingBallsMain2 app = new BouncingB...
//create a new file for storing position and velocit...
public static java.io.File file = new java.io.File("...
public static java.io.PrintWriter output;
public static java.io.File file2 = new java.io.File(...
public static java.io.PrintWriter output2;
// initiate the objects for generating random numbers
private Random positionGenerator = new Random();
private Random velGenerator = new Random();
private Random posNegGenerator = new Random();
private Random gravGenerator = new Random();
private Vector3f pt; // 3D vector position of bal...
private String hit; // which the object ball hits
// intiate the variable for storing time
long startTime;
long startGravTime;
long estimatedTime;
// variable determines whether gravity is universal
// or seperate for the balls
boolean randGrav = false;
private BitmapText gravText;
// Set the number of generated balls
final int NUMBALLS = 8;
// Set the initial velocity in XYZ
final int IVX = 5;
final int IVY = 5;
final int IVZ = 5;
// intiate the objects that will allow for the appli...
private BulletAppState bulletAppState;
private RigidBodyControl[] ball_physics = new RigidB...
BouncingBallsMain2.BallTextDisplay[] ballDisplays = ...
public static void main(String[] args) throws Except...
output = new java.io.PrintWriter(file);
output2 = new java.io.PrintWriter(file2);
app.start(); // start the game
}
@Override
public void simpleInitApp() {
bulletAppState = new BulletAppState();
stateManager.attach(bulletAppState);
bulletAppState.getPhysicsSpace().addCollisionLis...
// Set the location of the camera to be in one o...
// top corners of the cube looking in towards th...
cam.setLocation(new Vector3f(45, 40, 40));
cam.lookAt(new Vector3f(0, 0, 0), Vector3f.UNIT_...
flyCam.setEnabled(true);
flyCam.setMoveSpeed(10);
// Start the timer
startTime = System.currentTimeMillis();
startGravTime = System.currentTimeMillis();
BouncingBallsMain2.SphereObj[] sphereObjects = n...
//Create the spheres
for (int i = 0; i < NUMBALLS; i++) {
if (i < 2) {
// posX: -15 to -10, posY: -3 to 2, posZ...
sphereObjects[i] = new BouncingBallsMain...
}
else if(i < 4) {
// posX: -5 to 0, posY: -3 to 2, posZ: -...
sphereObjects[i] = new BouncingBallsMain...
}
else if (i < 6) {
// posX: 5 to 10, posY: -3 to 2, posZ: -...
sphereObjects[i] = new BouncingBallsMain...
}
else {
// posX: 15 to 20, posY: -3 to 2, posZ: ...
sphereObjects[i] = new BouncingBallsMain...
}
}
// Give the balls a physical presence
for (int i = 0; i < NUMBALLS; i++) {
ball_physics[i] = new RigidBodyControl(1f);
}
// Add the balls to the scene
for (int i = 0; i < NUMBALLS; i++) {
sphereObjects[i].addControl(ball_physics[i]);
}
for (int i = 0; i < NUMBALLS; i++) {
bulletAppState.getPhysicsSpace().add(ball_ph...
}
// Make the balls bouncy
for (int i = 0; i < NUMBALLS; i++) {
ball_physics[i].setRestitution(1.5f);
}
// Add the fllor, walls, and ceiling to the scene
BouncingBallsMain2.WallObj floor1 = new Bouncing...
BouncingBallsMain2.WallObj floor2 = new Bouncing...
BouncingBallsMain2.WallObj floor3 = new Bouncing...
//BouncingBallsMain2.WallObj floor4 = new Bounci...
BouncingBallsMain2.WallObj floor4 = new Bouncing...
BouncingBallsMain2.WallObj floor5 = new Bouncing...
BouncingBallsMain2.WallObj floor6 = new Bouncing...
BouncingBallsMain2.WallObj floor7 = new Bouncing...
BouncingBallsMain2.WallObj wall1 = new BouncingB...
BouncingBallsMain2.WallObj wall1_1 = new Bouncin...
BouncingBallsMain2.WallObj wall1_2 = new Bouncin...
BouncingBallsMain2.WallObj wall2 = new BouncingB...
BouncingBallsMain2.WallObj wall2_1 = new Bouncin...
BouncingBallsMain2.WallObj wall2_2 = new Bouncin...
BouncingBallsMain2.WallObj wall2_3 = new Bouncin...
BouncingBallsMain2.WallObj wall2_4 = new Bouncin...
BouncingBallsMain2.WallObj wall2_5 = new Bouncin...
BouncingBallsMain2.WallObj wall2_6 = new Bouncin...
BouncingBallsMain2.WallObj wall2_7 = new Bouncin...
BouncingBallsMain2.WallObj wall2_8 = new Bouncin...
BouncingBallsMain2.WallObj wall2_9 = new Bouncin...
BouncingBallsMain2.WallObj wall2_10 = new Bounci...
BouncingBallsMain2.WallObj wall2_11 = new Bounci...
BouncingBallsMain2.WallObj wall3 = new BouncingB...
BouncingBallsMain2.WallObj wall3_1 = new Bouncin...
BouncingBallsMain2.WallObj wall3_2 = new Bouncin...
BouncingBallsMain2.WallObj wall4 = new BouncingB...
BouncingBallsMain2.WallObj wall4_1 = new Bouncin...
BouncingBallsMain2.WallObj wall4_2 = new Bouncin...
BouncingBallsMain2.WallObj wall4_3 = new Bouncin...
BouncingBallsMain2.WallObj wall4_4 = new Bouncin...
BouncingBallsMain2.WallObj wall4_5 = new Bouncin...
BouncingBallsMain2.WallObj wall4_6 = new Bouncin...
BouncingBallsMain2.WallObj wall4_7 = new Bouncin...
BouncingBallsMain2.WallObj wall4_8 = new Bouncin...
BouncingBallsMain2.WallObj wall4_9 = new Bouncin...
BouncingBallsMain2.WallObj wall4_10 = new Bounci...
BouncingBallsMain2.WallObj wall4_11 = new Bounci...
BouncingBallsMain2.WallObj roof = new BouncingBa...
//BouncingBallsMain2.WallObj roof_1 = new Bounci...
BouncingBallsMain2.WallObj roof_1 = new Bouncing...
BouncingBallsMain2.WallObj roof_2 = new Bouncing...
BouncingBallsMain2.WallObj roof_3 = new Bouncing...
BouncingBallsMain2.WallObj roof_4 = new Bouncing...
BouncingBallsMain2.WallObj roof_5 = new Bouncing...
BouncingBallsMain2.WallObj roof_6 = new Bouncing...
// Generate the same gravity for all the balls
Vector3f worldGrav = generateRandomGravity();
// Set the gravity and random velocity to all th...
for (int i = 0; i < NUMBALLS; i++) {
if (randGrav) {
ball_physics[i].setGravity(generateRando...
}
else {
ball_physics[i].setGravity(worldGrav);
}
estimatedTime = System.currentTimeMillis() -...
// Set the initial velocity to all the balls
ball_physics[i].setLinearVelocity(new Vector...
if (estimatedTime > 500) {
// Set the random velocity to all the ba...
ball_physics[i].setLinearVelocity(genera...
}
}
// Remove the default text display from the gui.
guiNode.detachAllChildren();
setDisplayStatView(false);
setDisplayFps(false);
guiFont = assetManager.loadFont("Interface/Fonts...
// Add the text for tracking the balls' location...
for (int i = 0; i < NUMBALLS; i++) {
ballDisplays[i] = new BouncingBallsMain2.Bal...
}
gravText = new BitmapText(guiFont, false);
gravText.setSize(guiFont.getCharSet().getRendere...
if (randGrav) {
gravText.setText("Separate Gravity");
}
else {
gravText.setText("Universal Gravity");
}
gravText.setLocalTranslation(50, 50, 0);
guiNode.attachChild(gravText);
// Customize the keys
initKeys();
}
// Make it so that pressing P will exit the game
// If P is not used to exit the game, then the
// position and velocity data on the playthrough
// will not be saved and the text file will be
// blank
// Make it so that pressing G will switch gravity
// between universal and individual
public void initKeys() {
inputManager.addMapping("Exit", new KeyTrigger(...
inputManager.addListener(actionListener, new Str...
inputManager.addMapping("Gravity", new KeyTrigge...
inputManager.addListener(actionListener, new Str...
}
private ActionListener actionListener = new ActionLi...
public void onAction(String name, boolean keyPre...
if (name.equals("Exit") && !keyPressed) {
output.close();
output2.close();
app.stop();
}
if (name.equals("Gravity") && !keyPressed) {
randGrav = !randGrav;
}
}
};
// An event handler to detect collisions
public void collision(PhysicsCollisionEvent event) {
CollisionResults results = new CollisionResults();
Ray ray = new Ray(cam.getLocation(), cam.getDire...
rootNode.collideWith(ray, results); // detect...
if (results.size() > 0) {
for (int i = 0; i < results.size(); i++) {
pt = results.getCollision(i).getContactP...
hit = results.getCollision(i).getGeometr...
// ** Test code beginning
// output2.println(hit + ": " + pt);
output2.println(hit + " " + pt);
// ** Test code end
System.out.println("----- Collision # " ...
System.out.println("A ball hits " + hit ...
}
}
}
// The update loop for changing the text display in r...
// and for calling the method for recording positio...
// velocity, and gravity data on the current playth...
@Override
public void simpleUpdate(float tpf) {
estimatedTime = System.currentTimeMillis() - sta...
long estimatedGravTime = System.currentTimeMilli...
// Commented out below
/* System.out.println(estimatedTime + ", " + sta...
int elapsedTime = 0;
// if one second has elapsed in game
if(estimatedTime > 1000) {
// update the gui and record position and ve...
// to the text file
updatePositionDisplay();
for (int i = 0; i < NUMBALLS; i++) {
output.println("B" + i + ": " + getBallP...
}
startTime = System.currentTimeMillis();
}
// otherwise, only update the gui
else {
updatePositionDisplay();
}
// if at least 5 seconds has elapsed from the la...
// the gravity. If randGrav true, then each ball...
// gravity. Otherwise, change the world gravity.
if(estimatedGravTime > 5000) {
Vector3f worldGrav = generateRandomGravity();
for (int i = 0; i < NUMBALLS; i++) {
if (randGrav){
ball_physics[i].setGravity(generateR...
}
else {
ball_physics[i].setGravity(worldGrav);
}
}
startGravTime = System.currentTimeMillis();
}
}
// set the text on the gui display
public void updatePositionDisplay() {
for (int i = 0; i < NUMBALLS; i++) {
ballDisplays[i].setText(ball_physics[i]);
}
if (randGrav) {
gravText.setText("Separate Gravity");
}
else {
gravText.setText("Universal Gravity");
}
}
// generates a random velocity for a ball
public Vector3f generateRandomVelocity() {
float velx = velGenerator.nextInt(10);
int posNeg = posNegGenerator.nextInt(2);
if (posNeg == 0) {
velx *= -1;
}
float vely = velGenerator.nextInt(10);
posNeg = posNegGenerator.nextInt(2);
if (posNeg == 0) {
vely *= -1;
}
float velz = velGenerator.nextInt(10);
posNeg = posNegGenerator.nextInt(2);
if (posNeg == 0) {
velz *= -1;
}
return new Vector3f( velx , vely , velz );
}
// generates a random gravity for all of the balls
// or for each ball separately
public Vector3f generateRandomGravity() {
float gravX = gravGenerator.nextInt(3);
int posNeg = posNegGenerator.nextInt(2);
if (posNeg == 0) {
gravX *= -1;
}
float gravY = gravGenerator.nextInt(3);
posNeg = posNegGenerator.nextInt(2);
if (posNeg == 0) {
gravY *= -1;
}
float gravZ = gravGenerator.nextInt(3);
posNeg = posNegGenerator.nextInt(2);
if (posNeg == 0) {
gravZ *= -1;
}
return new Vector3f(gravX, gravY, gravZ);
}
// generates a random position
public int generateRandomPos() {
int pos = positionGenerator.nextInt(6);
return pos;
}
public String getBallPosString(RigidBodyControl ball...
String xPos = String.format("%5.2f", ball_physic...
String yPos = String.format("%5.2f", ball_physic...
String zPos = String.format("%5.2f", ball_physic...
// ** Test code beginning
// return "(" + xPos + ", " + yPos + ", " + zPos ...
return xPos + " " + yPos + " " + zPos;
// ** Test code end
}
// the sphere sphere object
public class SphereObj {
Vector3f position;
Sphere sphere;
Geometry geomSphere;
Material mat;
// constructor method that generates the sphere
SphereObj(String color, int minX) {
// the balls' radius are 0.5
sphere = new Sphere(32, 32, 0.5f);
geomSphere = new Geometry("Sphere", sphere);
mat = new Material(assetManager,
"Common/MatDefs/Misc/Unshaded.j3md");
if (color.equalsIgnoreCase("yellow")) {
mat.setColor("Color", ColorRGBA.Yellow);
} else if (color.equalsIgnoreCase("red")) {
mat.setColor("Color", ColorRGBA.Red);
} else if (color.equalsIgnoreCase("green")) {
mat.setColor("Color", ColorRGBA.Green);
} else {
mat.setColor("Color", new ColorRGBA(1, 0...
}
geomSphere.setMaterial(mat);
rootNode.attachChild(geomSphere);
int posX = minX + generateRandomPos();
int posY = -3 + generateRandomPos();
int posZ = -3 + generateRandomPos();
geomSphere.move(posX, posY, posZ);
}
// method that adds the physics aspects to the s...
public void addControl(RigidBodyControl ball_phy...
geomSphere.addControl(ball_phy);
}
}
// the wall class
public class WallObj {
Vector3f position;
Box box;
Geometry geomWall;
Material mat;
private RigidBodyControl phy;
// constructor that generates a wall object
// the parameters are the dimensions of the wall...
// and the translations the wall undergoes
WallObj(float x, float y, float z, String name, ...
box = new Box(Vector3f.ZERO, x, y, z);
box.scaleTextureCoordinates(new Vector2f(3, ...
geomWall = new Geometry(name, box);
mat = new Material(assetManager,
"Common/MatDefs/Misc/Unshaded.j3md");...
//set color of wall with alpha channel so ca...
if (color.equalsIgnoreCase("blue")) {
mat.setColor("Color", new ColorRGBA(0, 0...
} else if (color.equalsIgnoreCase("pink")) {
mat.setColor("Color", new ColorRGBA(1f, ...
} else if (color.equalsIgnoreCase("orange")) {
mat.setColor("Color", new ColorRGBA(.98f...
}
// make walls translucent
mat.getAdditionalRenderState().setBlendMode(...
geomWall.setMaterial(mat);
geomWall.setQueueBucket(Bucket.Translucent);
// move wall to position
geomWall.setLocalTranslation(xTrans, yTrans,...
rootNode.attachChild(geomWall);
phy = new RigidBodyControl(0.0f);
geomWall.addControl(phy);
bulletAppState.getPhysicsSpace().add(phy);
phy.setRestitution(0.5f);
}
// method that adds physics components to a wall
public void addControl(RigidBodyControl wall_phy...
geomWall.addControl(wall_phy);
}
}
// This class displays the text to the GUI
public class BallTextDisplay {
BitmapText ballText;
BitmapText gravText;
int ballNumber;
// This displays the positions of each ball sepa...
BallTextDisplay(int whichBall, float xPos, float...
ballText = new BitmapText(guiFont, false);
ballText.setSize(guiFont.getCharSet().getRe...
ballText.setText("B" + whichBall + ": ");
ballNumber = whichBall;
ballText.setLocalTranslation(xPos, yPos, zP...
guiNode.attachChild(ballText);
}
// This displays the positions of each ball sepa...
public void setText(RigidBodyControl ball_phy) {
String xPos = String.format("%5.2f", ball_phy...
String yPos = String.format("%5.2f", ball_phy...
String zPos = String.format("%5.2f", ball_phy...
ballText.setText("B" + ballNumber + ": (" + x...
}
}
}
- [[YouTube Video:https://www.youtube.com/watch?v=JSuMY9f...
- Test Data
#ref(BouncingBalls2TestData.pdf)
** Week 7 Social Anxiety [#x9b258fc]
- Question
A social gaming. Like it or hate it, it is one of the maj...
- Answer
From the view point of an user, I like the trend. You can...
From the view point of a social game provider, social gam...
It is harder to make users lock in a specific platform be...
The business model was drastically changed. Prices of a g...
** Week 8 Sequels [#a371cc26]
- Question
While networking and multiplayer aspects were not require...
What kind of game would you develop for this course? Woul...
- Answer
Because I am interested in more infrastructure side such ...
Since I learned 3D Java game programming using jMonkeyEng...
** Week 8 Final Project [#q7e618c2]
Students will use a popular, freely distributed game plat...
''Requirements:''
Using the 3D graphics and associated Physics engine devel...
+ At least 4 types of targets should be displayed in the ...
+ Each of the targets should be moving in the scene.
+ At least one of the targets should have gravity/physics...
+ Bullets or missiles should be unlimited.
+ A Heads-up Display should be provided with a minimum of...
+ High score should be stored in an ASCII file. Optionall...
+ Simple directions for running the game should be includ...
+ A game timer should be embedded limiting a game session...
+ Coding conventions should be followed based on the prog...
''Deliverables include:''
-- All source code in winzip format
-- Compile and run instructions
-- Well-written word document describing:
--- Your overall design
--- Your test plan, including test data and results
--- Your approach, lessons learned, design strengths, lim...
- Target.java
import com.jme3.asset.AssetManager;
import com.jme3.bullet.BulletAppState;
import com.jme3.bullet.control.RigidBodyControl;
import com.jme3.material.Material;
import com.jme3.math.ColorRGBA;
import com.jme3.scene.Geometry;
import com.jme3.scene.Node;
import com.jme3.scene.shape.Sphere;
import java.util.Random;
/*
* This class creates shootable objects made of four sph...
* The colors and locations of each sphere are randomly ...
* @author yujishimojo
*/
public final class Target {
private BulletAppState bulletAppState;
private Node rootNode;
private Node shootables;
private AssetManager assetManager;
public Geometry outlineBall1;
public Geometry outlineBall2;
public Geometry outlineBall3;
public Geometry outlineBall4;
public RigidBodyControl ballCollision1;
public RigidBodyControl ballCollision2;
public RigidBodyControl ballCollision3;
public RigidBodyControl ballCollision4;;
public Target (AssetManager assetManager, Node rootN...
this.bulletAppState = bulletAppState;
this.rootNode = rootNode;
this.shootables = shootables;
this.assetManager = assetManager;
rootNode.attachChild(shootables);
// Creates balls
createBall1();
createBall2();
createBall3();
createBall4();
}
public void createBall1() {
Random random = new Random();
Sphere createBall = new Sphere(32, 32, 0.8f);
outlineBall1 = new Geometry("Ball 1", createBall);
createBall.setTextureMode(Sphere.TextureMode.Pro...
Material mat = new Material(assetManager,
"Common/MatDefs/Misc/Unshaded.j3md");
mat.setColor("Color", ColorRGBA.randomColor());
outlineBall1.setMaterial(mat);
outlineBall1.setLocalTranslation((random.nextFlo...
shootables.attachChild(outlineBall1);
ballCollision1 = new RigidBodyControl(1f);
outlineBall1.addControl(ballCollision1);
bulletAppState.getPhysicsSpace().add(ballCollisi...
ballCollision1.setMass(1);
ballCollision1.setFriction(0);
ballCollision1.setRestitution(1.0f);
}
public void createBall2() {
Random random = new Random();
Sphere createBall = new Sphere(32, 32, 0.6f);
outlineBall2 = new Geometry("Ball 2", createBall);
createBall.setTextureMode(Sphere.TextureMode.Pro...
Material mat = new Material(assetManager,
"Common/MatDefs/Misc/Unshaded.j3md");
mat.setColor("Color", ColorRGBA.randomColor());
outlineBall2.setMaterial(mat);
outlineBall2.setLocalTranslation((random.nextFlo...
shootables.attachChild(outlineBall2);
ballCollision2 = new RigidBodyControl(1f);
outlineBall2.addControl(ballCollision2);
bulletAppState.getPhysicsSpace().add(ballCollisi...
ballCollision2.setMass(1);
ballCollision2.setFriction(0);
ballCollision2.setRestitution(1.0f);
}
public void createBall3() {
Random random = new Random();
Sphere createBall = new Sphere(32, 32, 0.4f);
outlineBall3 = new Geometry("Ball 3", createBall);
createBall.setTextureMode(Sphere.TextureMode.Pro...
Material mat = new Material(assetManager,
"Common/MatDefs/Misc/Unshaded.j3md");
mat.setColor("Color", ColorRGBA.randomColor());
outlineBall3.setMaterial(mat);
outlineBall3.setLocalTranslation((random.nextFlo...
shootables.attachChild(outlineBall3);
ballCollision3 = new RigidBodyControl(1f);
outlineBall3.addControl(ballCollision3);
bulletAppState.getPhysicsSpace().add(ballCollisi...
ballCollision3.setMass(1);
ballCollision3.setFriction(0);
ballCollision3.setRestitution(1.0f);
}
public void createBall4() {
Random random = new Random();
Sphere createBall = new Sphere(32, 32, 0.2f);
outlineBall4 = new Geometry("Ball 4", createBall);
createBall.setTextureMode(Sphere.TextureMode.Pro...
Material mat = new Material(assetManager,
"Common/MatDefs/Misc/Unshaded.j3md");
mat.setColor("Color", ColorRGBA.randomColor());
outlineBall4.setMaterial(mat);
outlineBall4.setLocalTranslation((random.nextFlo...
shootables.attachChild(outlineBall4);
ballCollision4 = new RigidBodyControl(1f);
outlineBall4.addControl(ballCollision4);
bulletAppState.getPhysicsSpace().add(ballCollisi...
ballCollision4.setMass(1);
ballCollision4.setFriction(0);
ballCollision4.setRestitution(1.0f);
}
}
- Cube.java
import com.jme3.asset.AssetManager;
import com.jme3.bullet.BulletAppState;
import com.jme3.bullet.control.RigidBodyControl;
import com.jme3.material.Material;
import com.jme3.material.RenderState;
import com.jme3.math.ColorRGBA;
import com.jme3.math.FastMath;
import com.jme3.math.Quaternion;
import com.jme3.math.Vector2f;
import com.jme3.math.Vector3f;
import com.jme3.scene.Geometry;
import com.jme3.scene.Mesh;
import com.jme3.scene.Node;
import com.jme3.scene.VertexBuffer;
import com.jme3.util.BufferUtils;
/*
* This class creates cubic scene objects made of six si...
* @author yujishimojo
*/
public class Cube {
private BulletAppState bulletAppState;
private Node rootNode;
private AssetManager assetManager;
public Cube (AssetManager assetManager, Node rootNod...
this.bulletAppState = bulletAppState;
this.rootNode = rootNode;
this.assetManager = assetManager;
// Create back side of cube
createBackCube();
// Create front side of cube
createFrontCube();
// Create right side of cube
createRightSideCube();
// Create left side of cube
createLeftSideCube();
// Create bottom side of cube
createBottomSideCube();
// Create top side of cube
createTopSideCube();
}
private void createBackCube() {
Mesh back = new Mesh();
// Back Wall
Vector3f[] backVertices = new Vector3f[4];
backVertices[0] = new Vector3f(0, 0, 0);
backVertices[1] = new Vector3f(9, 0, 0);
backVertices[2] = new Vector3f(0, 9, 0);
backVertices[3] = new Vector3f(9, 9, 0);
// Back Wall
Vector2f[] backCoord = new Vector2f[4];
backCoord[0] = new Vector2f(0, 0);
backCoord[1] = new Vector2f(1, 0);
backCoord[2] = new Vector2f(0, 1);
backCoord[3] = new Vector2f(1, 1);
// Indexes. We define the order in which mesh sh...
int[] indexes = {2, 0, 1, 1, 3, 2};
// Setting buffers
back.setBuffer(VertexBuffer.Type.Position, 3, Bu...
back.setBuffer(VertexBuffer.Type.TexCoord, 2, Bu...
back.setBuffer(VertexBuffer.Type.Index, 1, Buffe...
back.updateBound();
// Create back of cube
Geometry backGeom = new Geometry("OurMesh", back);
Material backMat = new Material(assetManager, "C...
backMat.setColor("Color", ColorRGBA.White);
backGeom.setMaterial(backMat);
backMat.getAdditionalRenderState().setWireframe(...
backMat.getAdditionalRenderState().setFaceCullMo...
rootNode.attachChild(backGeom);
RigidBodyControl backWallCollision = new RigidBo...
backGeom.addControl(backWallCollision);
bulletAppState.getPhysicsSpace().add(backWallCol...
backWallCollision.setRestitution(0.15f);
backWallCollision.setFriction(0);
}
private void createFrontCube() {
Mesh front = new Mesh();
// Front Wall
Vector3f[] frontVertices = new Vector3f[4];
frontVertices[0] = new Vector3f(0, 0, 9);
frontVertices[1] = new Vector3f(9, 0, 9);
frontVertices[2] = new Vector3f(0, 9, 9);
frontVertices[3] = new Vector3f(9, 9, 9);
// Front Wall
Vector2f[] frontCoord = new Vector2f[4];
frontCoord[0] = new Vector2f(0, 0);
frontCoord[1] = new Vector2f(1, 0);
frontCoord[2] = new Vector2f(0, 1);
frontCoord[3] = new Vector2f(1, 1);
// Indexes. We define the order in which mesh sh...
int[] indexes = {2, 0, 1, 1, 3, 2};
// Setting buffers
front.setBuffer(VertexBuffer.Type.Position, 3, B...
front.setBuffer(VertexBuffer.Type.TexCoord, 2, B...
front.setBuffer(VertexBuffer.Type.Index, 1, Buff...
front.updateBound();
// Create front of cube
Geometry frontGeom = new Geometry("OurMesh", fro...
Material frontMat = new Material(assetManager, "...
frontGeom.setMaterial(frontMat);
frontMat.setTransparent(true);
frontMat.getAdditionalRenderState().setFaceCullM...
rootNode.attachChild(frontGeom);
RigidBodyControl frontWallCollision = new RigidB...
frontGeom.addControl(frontWallCollision);
bulletAppState.getPhysicsSpace().add(frontWallCo...
frontWallCollision.setRestitution(0.15f);
frontWallCollision.setFriction(0);
}
private void createRightSideCube() {
Mesh rightSide = new Mesh();
Quaternion quatA = new Quaternion();
quatA.fromAngleAxis(-FastMath.HALF_PI, Vector3f....
// Right Wall
Vector3f[] rightSideVertices = new Vector3f[4];
rightSideVertices[0] = new Vector3f(3, 0, -9);
rightSideVertices[1] = new Vector3f(12, 0, -9);
rightSideVertices[2] = new Vector3f(3, 9, -9);
rightSideVertices[3] = new Vector3f(12, 9, -9);
Vector3f vectorA = quatA.mult(rightSideVertices[...
Vector3f vectorB = quatA.mult(rightSideVertices[...
Vector3f vectorC = quatA.mult(rightSideVertices[...
Vector3f vectorD = quatA.mult(rightSideVertices[...
Vector3f[] rightSideYes = new Vector3f[4];
rightSideYes[0] = new Vector3f(vectorA);
rightSideYes[1] = new Vector3f(vectorB);
rightSideYes[2] = new Vector3f(vectorC);
rightSideYes[3] = new Vector3f(vectorD);
// Right Wall
Vector2f[] rightSideCoord = new Vector2f[4];
rightSideCoord[0] = new Vector2f(0, 0);
rightSideCoord[1] = new Vector2f(1, 0);
rightSideCoord[2] = new Vector2f(0, 1);
rightSideCoord[3] = new Vector2f(1, 1);
// Indexes. We define the order in which mesh sh...
int[] indexes = {2, 0, 1, 1, 3, 2};
// Setting buffers
rightSide.setBuffer(VertexBuffer.Type.Position, ...
rightSide.setBuffer(VertexBuffer.Type.TexCoord, ...
rightSide.setBuffer(VertexBuffer.Type.Index, 1, ...
rightSide.updateBound();
// Create Right of cube
Geometry rightSideGeom = new Geometry("OurMesh",...
rightSideGeom.setLocalTranslation(0, 0, -3);
Material rightSideMat = new Material(assetManage...
rightSideMat.setColor("Color", ColorRGBA.White);
rightSideGeom.setMaterial(rightSideMat);
rightSideMat.getAdditionalRenderState().setWiref...
rightSideMat.getAdditionalRenderState().setFaceC...
RigidBodyControl rightWallCollision = new RigidB...
rightSideGeom.addControl(rightWallCollision);
bulletAppState.getPhysicsSpace().add(rightWallCo...
rightWallCollision.setRestitution(0.15f);
rightWallCollision.setFriction(0);
rootNode.attachChild(rightSideGeom);
}
private void createLeftSideCube() {
Mesh leftSide = new Mesh();
Quaternion quatA = new Quaternion();
quatA.fromAngleAxis(-FastMath.HALF_PI, Vector3f....
// Left Wall
Vector3f[] leftSideVertices = new Vector3f[4];
leftSideVertices[0] = new Vector3f(6, 0, 0);
leftSideVertices[1] = new Vector3f(-3, 0, 0);
leftSideVertices[2] = new Vector3f(6, 9, 0);
leftSideVertices[3] = new Vector3f(-3, 9, 0);
Vector3f vectorA = quatA.mult(leftSideVertices[0...
Vector3f vectorB = quatA.mult(leftSideVertices[1...
Vector3f vectorC = quatA.mult(leftSideVertices[2...
Vector3f vectorD = quatA.mult(leftSideVertices[3...
Vector3f[] leftSideYes = new Vector3f[4];
leftSideYes[0] = new Vector3f(vectorA);
leftSideYes[1] = new Vector3f(vectorB);
leftSideYes[2] = new Vector3f(vectorC);
leftSideYes[3] = new Vector3f(vectorD);
// Left Wall
Vector2f[] leftSideCoord = new Vector2f[4];
leftSideCoord[0] = new Vector2f(0, 0);
leftSideCoord[1] = new Vector2f(1, 0);
leftSideCoord[2] = new Vector2f(0, 1);
leftSideCoord[3] = new Vector2f(1, 1);
// Indexes. We define the order in which mesh sh...
int[] indexes = {2, 0, 1, 1, 3, 2};
// Setting buffers
leftSide.setBuffer(VertexBuffer.Type.Position, 3...
leftSide.setBuffer(VertexBuffer.Type.TexCoord, 2...
leftSide.setBuffer(VertexBuffer.Type.Index, 1, B...
leftSide.updateBound();
// Create Left of cube
Geometry leftSideGeom = new Geometry("OurMesh", ...
Material leftSideMat = new Material(assetManager...
leftSideMat.setColor("Color", ColorRGBA.White);
leftSideGeom.setMaterial(leftSideMat);
leftSideGeom.setLocalTranslation(0, 0, 3);
leftSideMat.getAdditionalRenderState().setWirefr...
leftSideMat.getAdditionalRenderState().setFaceCu...
rootNode.attachChild(leftSideGeom);
RigidBodyControl leftWallCollision = new RigidBo...
leftSideGeom.addControl(leftWallCollision);
bulletAppState.getPhysicsSpace().add(leftWallCol...
leftWallCollision.setRestitution(0.15f);
leftWallCollision.setFriction(0);
}
private void createBottomSideCube() {
Mesh bottomSide = new Mesh();
Quaternion quatA = new Quaternion();
quatA.fromAngleAxis(-FastMath.HALF_PI, Vector3f....
// Bottom Wall
Vector3f[] bottomSideVertices = new Vector3f[4];
bottomSideVertices[0] = new Vector3f(0, 0, 9);
bottomSideVertices[1] = new Vector3f(0, -9, 9);
bottomSideVertices[2] = new Vector3f(9, 0, 9);
bottomSideVertices[3] = new Vector3f(9, -9, 9);
Vector3f vectorA = quatA.mult(bottomSideVertices...
Vector3f vectorB = quatA.mult(bottomSideVertices...
Vector3f vectorC = quatA.mult(bottomSideVertices...
Vector3f vectorD = quatA.mult(bottomSideVertices...
Vector3f[] bottomSideYes = new Vector3f[4];
bottomSideYes[0] = new Vector3f(vectorA);
bottomSideYes[1] = new Vector3f(vectorB);
bottomSideYes[2] = new Vector3f(vectorC);
bottomSideYes[3] = new Vector3f(vectorD);
// Bottom Wall
Vector2f[] bottomSideCoord = new Vector2f[4];
bottomSideCoord[0] = new Vector2f(0, 0);
bottomSideCoord[1] = new Vector2f(1, 0);
bottomSideCoord[2] = new Vector2f(0, 1);
bottomSideCoord[3] = new Vector2f(1, 1);
// Indexes. We define the order in which mesh sh...
int[] indexes = {2, 0, 1, 1, 3, 2};
// Setting buffers
bottomSide.setBuffer(VertexBuffer.Type.Position,...
bottomSide.setBuffer(VertexBuffer.Type.TexCoord,...
bottomSide.setBuffer(VertexBuffer.Type.Index, 1,...
bottomSide.updateBound();
// Create Bottom of cube
Geometry bottomSideGeom = new Geometry("OurMesh"...
Material bottomSideMat = new Material(assetManag...
bottomSideMat.setColor("Color", ColorRGBA.White);
bottomSideGeom.setMaterial(bottomSideMat);
bottomSideMat.getAdditionalRenderState().setWire...
bottomSideMat.getAdditionalRenderState().setFace...
rootNode.attachChild(bottomSideGeom);
RigidBodyControl bottomWallCollision = new Rigid...
bottomSideGeom.addControl(bottomWallCollision);
bulletAppState.getPhysicsSpace().add(bottomWallC...
bottomWallCollision.setRestitution(0.15f);
bottomWallCollision.setFriction(0);
}
private void createTopSideCube() {
Mesh topSide = new Mesh();
Quaternion quatA = new Quaternion();
quatA.fromAngleAxis(-FastMath.HALF_PI, Vector3f....
// Top Wall
Vector3f[] topSideVertices = new Vector3f[4];
topSideVertices[0] = new Vector3f(0, 0, 0);
topSideVertices[1] = new Vector3f(0, -9, 0);
topSideVertices[2] = new Vector3f(9, 0, 0);
topSideVertices[3] = new Vector3f(9, -9, 0);
Vector3f vectorA = quatA.mult(topSideVertices[0]);
Vector3f vectorB = quatA.mult(topSideVertices[1]);
Vector3f vectorC = quatA.mult(topSideVertices[2]);
Vector3f vectorD = quatA.mult(topSideVertices[3]);
Vector3f[] topSideYes = new Vector3f[4];
topSideYes[0] = new Vector3f(vectorA);
topSideYes[1] = new Vector3f(vectorB);
topSideYes[2] = new Vector3f(vectorC);
topSideYes[3] = new Vector3f(vectorD);
// Top Wall
Vector2f[] topSideCoord = new Vector2f[4];
topSideCoord[0] = new Vector2f(0, 0);
topSideCoord[1] = new Vector2f(1, 0);
topSideCoord[2] = new Vector2f(0, 1);
topSideCoord[3] = new Vector2f(1, 1);
// Indexes. We define the order in which mesh sh...
int[] indexes = {2, 0, 1, 1, 3, 2};
// Setting buffers
topSide.setBuffer(VertexBuffer.Type.Position, 3,...
topSide.setBuffer(VertexBuffer.Type.TexCoord, 2,...
topSide.setBuffer(VertexBuffer.Type.Index, 1, Bu...
topSide.updateBound();
// Create Top of cube
Geometry topSideGeom = new Geometry("OurMesh", t...
Material topSideMat = new Material(assetManager,...
topSideMat.setColor("Color", ColorRGBA.White);
topSideGeom.setMaterial(topSideMat);
topSideMat.getAdditionalRenderState().setWirefra...
topSideMat.getAdditionalRenderState().setFaceCul...
RigidBodyControl topWallCollision = new RigidBod...
topSideGeom.addControl(topWallCollision);
bulletAppState.getPhysicsSpace().add(topWallColl...
topWallCollision.setFriction(0);
topWallCollision.setRestitution(0.15f);
rootNode.attachChild(topSideGeom);
}
}
- Weapon.java
import com.jme3.asset.AssetManager;
import com.jme3.asset.TextureKey;
import com.jme3.bullet.BulletAppState;
import com.jme3.bullet.control.RigidBodyControl;
import com.jme3.material.Material;
import com.jme3.math.ColorRGBA;
import com.jme3.math.Vector3f;
import com.jme3.scene.Geometry;
import com.jme3.scene.Node;
import com.jme3.scene.debug.Arrow;
import com.jme3.scene.shape.*;
import com.jme3.texture.Texture;
/*
* This class creates three types of weapons: a laser be...
* @author yujishimojo
*/
public class Weapon {
private BulletAppState bulletAppState;
private Node rootNode;
private AssetManager assetManager;
public Geometry geoLaserBeam;
public Geometry geoCannonBall;
public Geometry geoArrow;
public Material matLaserBeam;
public Material matCannonBall;
public Material matArrow;
public RigidBodyControl phyLaserBeam;
public RigidBodyControl phyCannonBall;
public RigidBodyControl phyArrow;
int VELOCITY = 100;
public Weapon (AssetManager assetManager, Node rootN...
this.bulletAppState = bulletAppState;
this.rootNode = rootNode;
this.assetManager = assetManager;
}
public void makeLaserBeam (Vector3f location, Vector...
Box createLaserBeam = new Box(Vector3f.ZERO, 0.1...
geoLaserBeam = new Geometry ("Laser Beam", creat...
matLaserBeam = new Material(assetManager, "Commo...
matLaserBeam.setColor("Color", new ColorRGBA(1.0...
geoLaserBeam.setMaterial(matLaserBeam);
rootNode.attachChild(geoLaserBeam);
geoLaserBeam.setLocalTranslation(location);
phyLaserBeam = new RigidBodyControl(1f);
geoLaserBeam.addControl(phyLaserBeam);
bulletAppState.getPhysicsSpace().add(phyLaserBea...
/** Accelerate the physcial ball to shoot it. */
phyLaserBeam.setLinearVelocity(direction.mult(VE...
phyLaserBeam.setGravity(new Vector3f(0, 0, 0));
}
public void removeLaserBeam () {
rootNode.detachChild(geoLaserBeam);
}
public void makeCannonBall (Vector3f location, Vecto...
/** Create a ball geometry. */
Sphere createCannonBall = new Sphere(32, 32, 0.3...
geoCannonBall = new Geometry("Cannon Ball", crea...
createCannonBall.setTextureMode(Sphere.TextureMo...
matCannonBall = new Material(assetManager, "Comm...
TextureKey key = new TextureKey("Textures/Terrai...
key.setGenerateMips(true);
Texture tex = assetManager.loadTexture(key);
matCannonBall.setTexture("ColorMap", tex);
geoCannonBall.setMaterial(matCannonBall);
rootNode.attachChild(geoCannonBall);
/** Position the ball */
geoCannonBall.setLocalTranslation(location);
/** Make the ball physcial with a mass > 0.0f */
phyCannonBall = new RigidBodyControl(1f);
/** Add physical ball to physics space. */
geoCannonBall.addControl(phyCannonBall);
bulletAppState.getPhysicsSpace().add(phyCannonBa...
/** Accelerate the physcial ball to shoot it. */
phyCannonBall.setLinearVelocity(direction.mult(V...
phyCannonBall.setGravity(new Vector3f(0, 0, 0));
}
public void removeCannonBall () {
rootNode.detachChild(geoCannonBall);
}
public void makeArrow (Vector3f location, Vector3f d...
Arrow createArrow = new Arrow(direction.mult(1));
createArrow.setLineWidth(2);
geoArrow = new Geometry("arrow", createArrow);
matArrow = new Material(assetManager, "Common/Ma...
matArrow.setColor("Color", new ColorRGBA(0.9f,0....
geoArrow.setMaterial(matArrow);
rootNode.attachChild(geoArrow);
geoArrow.setLocalTranslation(location);
phyArrow = new RigidBodyControl(1f);
geoArrow.addControl(phyArrow);
bulletAppState.getPhysicsSpace().add(phyArrow);
phyArrow.setLinearVelocity(direction.mult(VELOCI...
phyArrow.setGravity(new Vector3f(0, 0, 0));
}
public void removeArrow () {
rootNode.detachChild(geoArrow);
}
}
- ShootingObjectsMain.java
import com.jme3.app.SimpleApplication;
import com.jme3.audio.AudioNode;
import com.jme3.bullet.BulletAppState;
import com.jme3.collision.CollisionResults;
import com.jme3.font.BitmapText;
import com.jme3.input.KeyInput;
import com.jme3.input.MouseInput;
import com.jme3.input.controls.ActionListener;
import com.jme3.input.controls.KeyTrigger;
import com.jme3.input.controls.MouseButtonTrigger;
import com.jme3.math.Ray;
import com.jme3.math.Vector3f;
import com.jme3.scene.Node;
import java.util.Random;
import java.util.Timer;
import javax.swing.JOptionPane;
/*
* This is the main class of the project.
* The functions are: text display on the screen, file e...
* and event handlers for key presses and collision dete...
* @author yujishimojo
*/
public class ShootingObjectsMain extends SimpleApplicati...
private java.io.PrintWriter output;
private BulletAppState bulletAppState;
private Cube createCube;
private Target target;
private Weapon weapon;
private int count = 0;
Node shootables;
Timer timeClone;
private int gameTimeCount = 0;
private float shotsFired = 0;
private float shotsHit = 0;
private int destroyedTarget = 0;
private float shotAccuracy = 100;
private int points = 0;
int weaponState = 0;
BitmapText timePlayed;
BitmapText bulletsFired;
BitmapText bulletsHit;
BitmapText accuracy;
BitmapText targetsDestroyed;
BitmapText pointSum;
BitmapText selectedWeapon;
private int ball1 = 0;
private int ball2 = 0;
private int ball3 = 0;
private int ball4 = 0;
private AudioNode laserBeamAudio;
private AudioNode cannonBallAudio;
private AudioNode arrowAudio;
private AudioNode objectExplodeAudio;
public static void main(String[] args) {
ShootingObjectsMain shootingObjectsMain = new Sh...
// Starts the game
shootingObjectsMain.start();
}
@Override
public void simpleInitApp() {
// Declares string fileName to be used in if sta...
String fileName;
// Declares java.io.File file
java.io.File file;
// Configure cam to look at scene
cam.setLocation(new Vector3f(4.3f, 4.8f, 25f));
cam.lookAt(new Vector3f(4.5f, 4.5f, 0), Vector3f...
flyCam.setMoveSpeed(0);
bulletAppState = new BulletAppState();
stateManager.attach(bulletAppState);
bulletAppState.getPhysicsSpace().setAccuracy(0.0...
bulletAppState.getPhysicsSpace().setGravity(new ...
// Set up GUI
initCrosshair();
// Set up shooter
initKeys();
// Set up audio
initAudio();
// Create shootables node
shootables = new Node("shootables");
// Creates the first cube
createCube = new Cube(assetManager, rootNode, bu...
// Creates the first cube
target = new Target(assetManager, rootNode, shoo...
// Instantiate the Weapon class
weapon = new Weapon(assetManager, rootNode, bull...
// User determines file name
fileName = JOptionPane.showInputDialog(null, "Wh...
// Creates new file using new name
file = new java.io.File(fileName + "_ShootingObj...
// Instatiates geometries for weapons to avoid N...
weapon.makeLaserBeam(cam.getLocation(), cam.getD...
weapon.makeCannonBall(cam.getLocation(), cam.get...
weapon.makeArrow(cam.getLocation(), cam.getDirec...
try {
// Create a Scanner for the file
output = new java.io.PrintWriter(file);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void stop() {
output.println("Bullets Fired: " + shotsFired);
output.println("Bullets Hit: " + shotsHit);
output.println("Accuracy: " + shotAccuracy + "%");
output.println("Targets Destroyed: " + destroyed...
output.println("Points: " + points);
output.flush();
output.close();
System.exit(0);
}
@Override
public void simpleUpdate(float tpf) {
// Update selected weapon
updateWeaponDisplay();
// Update vector position to text file
if (getTimer().getTimeInSeconds() >= 1) {
getTimer().reset();
count++;
gameTimeCount++;
updateTime();
// Clear weapons to display one by one
weapon.removeLaserBeam();
weapon.removeCannonBall();
weapon.removeArrow();
// Gravity changes every 6 seconds.
if (count > 5) {
Random random = new Random();
Vector3f setGravity = new Vector3f((rand...
bulletAppState.getPhysicsSpace().setGrav...
System.out.println("Gravity Location" + ...
System.out.println("5 seconds");
bulletAppState.getPhysicsSpace().applyGr...
count = 0;
}
// Stops game automatically
if (gameTimeCount >= 120) {
JOptionPane.showMessageDialog(null, "Two...
// Shows the final results
JOptionPane.showMessageDialog(null,
"Bullets Fired: " + shotsFired +...
+ "Bullets Hit: " + shotsHit + "...
+ "Accuracy: " + shotAccuracy + ...
+ "Targets Destroyed: " + destro...
+ "Points: " + points,
"Results:", JOptionPane.INFORMAT...
stop();
}
}
}
// Creates key to shoot
private void initKeys() {
inputManager.addMapping("Shoot",
new KeyTrigger(KeyInput.KEY_SPACE), // t...
new MouseButtonTrigger(MouseInput.BUTTON...
inputManager.addListener(actionListener, "Shoot");
inputManager.addMapping("Laser", new KeyTrigger(...
inputManager.addListener(actionListener, new Str...
inputManager.addMapping("Cannon", new KeyTrigger...
inputManager.addListener(actionListener, new Str...
inputManager.addMapping("Arrow", new KeyTrigger(...
inputManager.addListener(actionListener, new Str...
}
// Create shooting action listener
private ActionListener actionListener = new ActionLi...
private int ws; // A local variable to manage we...
public void onAction(String name, boolean keyPre...
if (name.equals("Shoot") && !keyPressed) {
// Clear the weapon
if (ws == 0) {
weapon.removeLaserBeam();
} else if (ws == 1) {
weapon.removeCannonBall();
} else if (ws == 2) {
weapon.removeArrow();
}
// Makes the weapon
if (ws == 0) {
weapon.makeLaserBeam(cam.getLocation...
} else if (ws == 1) {
weapon.makeCannonBall(cam.getLocatio...
} else if (ws == 2) {
weapon.makeArrow(cam.getLocation(), ...
}
// This is for removing the weapon for c...
long startTime = System.currentTimeMilli...
// Plays shooting sound
if (ws == 0) {
laserBeamAudio.playInstance();
} else if (ws == 1) {
cannonBallAudio.playInstance();
} else if (ws == 2) {
arrowAudio.playInstance();
}
// Reset results list.
CollisionResults results = new Collision...
// Aim the ray from cam loc to cam direc...
Ray ray = new Ray(cam.getLocation(), cam...
// Collect intersections between Ray and...
shootables.collideWith(ray, results);
// If results is 0 then console prints y...
if (results.size() > 0) {
for (int i = 0; i < results.size(); ...
// Outputs results for all colli...
float dist = results.getCollisio...
Vector3f pt = results.getCollisi...
String hit = results.getCollisio...
// Removes the weapon within 0.01s
if (System.currentTimeMillis() -...
if (ws == 0) {
weapon.removeLaserBeam();
} else if (ws == 1) {
weapon.removeCannonBall(...
} else if (ws == 2) {
weapon.removeArrow();
}
startTime = 0;
}
createNewCubes(hit); ...
System.out.println("* Collision ...
System.out.println(" You shot "...
shotsHit++;
break;
}
} else {
System.out.println("You missed!");
}
// Update shots fired on GUI
shotsFired++;
updateShotsFired();
}
// Changes the value of the weapon state
if (name.equals("Laser") && !keyPressed) {
ws = 0;
weaponState = 0;
} else if (name.equals("Cannon") && !keyPres...
ws = 1;
weaponState = 1;
} else if (name.equals("Arrow") && !keyPress...
ws = 2;
weaponState = 2;
}
}
};
// Create audio to attach to scene
private void initAudio() {
laserBeamAudio = new AudioNode(assetManager, "So...
laserBeamAudio.setLooping(false);
laserBeamAudio.setVolume(2);
rootNode.attachChild(laserBeamAudio);
cannonBallAudio = new AudioNode(assetManager, "S...
cannonBallAudio.setLooping(false);
cannonBallAudio.setVolume(1);
rootNode.attachChild(cannonBallAudio);
arrowAudio = new AudioNode(assetManager, "Sounds...
arrowAudio.setLooping(false);
arrowAudio.setVolume(2);
rootNode.attachChild(arrowAudio);
objectExplodeAudio = new AudioNode(assetManager,...
objectExplodeAudio.setLooping(false);
objectExplodeAudio.setVolume(4);
rootNode.attachChild(objectExplodeAudio);
}
// Create shooting action attached to left mouse click
private void initCrosshair() {
guiNode.detachAllChildren();
guiFont = assetManager.loadFont("Interface/Fonts...
// Creates Crosshair
BitmapText ch = new BitmapText(guiFont, false);
ch.setSize(guiFont.getCharSet().getRenderedSize(...
ch.setText("+"); // crosshairs
ch.setLocalTranslation( // center
settings.getWidth() / 2 - guiFont.getCha...
settings.getHeight() / 2 + ch.getLineHei...
guiNode.attachChild(ch);
// Creates Time Played Text
timePlayed = new BitmapText(guiFont, false);
timePlayed.setSize(guiFont.getCharSet().getRende...
timePlayed.setText("Time: " + gameTimeCount + " ...
timePlayed.setLocalTranslation(0, 475, 0);
guiNode.attachChild(timePlayed);
// Creates Number of Bullets Fired Text
bulletsFired = new BitmapText(guiFont, false);
bulletsFired.setSize(guiFont.getCharSet().getRen...
bulletsFired.setText("Bullets Fired: " + shotsFi...
bulletsFired.setLocalTranslation(0, 450, 0);
guiNode.attachChild(bulletsFired);
// Creates Number of Bullets Hit Text
bulletsHit = new BitmapText(guiFont, false);
bulletsHit.setSize(guiFont.getCharSet().getRende...
bulletsHit.setText("Bullets Hit: " + shotsHit);
bulletsHit.setLocalTranslation(0, 425, 0);
guiNode.attachChild(bulletsHit);
// Creates Accuracy Text
accuracy = new BitmapText(guiFont, false);
accuracy.setSize(guiFont.getCharSet().getRendere...
accuracy.setText("Accuracy: " + shotAccuracy + "...
accuracy.setLocalTranslation(0, 400, 0);
guiNode.attachChild(accuracy);
// Creates Number of Targets Destroyed Text
targetsDestroyed = new BitmapText(guiFont, false);
targetsDestroyed.setSize(guiFont.getCharSet().ge...
targetsDestroyed.setText("Targets Destroyed: " +...
targetsDestroyed.setLocalTranslation(0, 375, 0);
guiNode.attachChild(targetsDestroyed);
// Creates Number of Targets Destroyed Text
pointSum = new BitmapText(guiFont, false);
pointSum.setSize(guiFont.getCharSet().getRendere...
pointSum.setText("Points: " + points);
pointSum.setLocalTranslation(0, 350, 0);
guiNode.attachChild(pointSum);
// Creates
selectedWeapon = new BitmapText(guiFont, false);
selectedWeapon.setSize(guiFont.getCharSet().getR...
selectedWeapon.setText("Laser Beam"); // default...
selectedWeapon.setLocalTranslation(540, 475, 0);
guiNode.attachChild(selectedWeapon);
}
private void updateTime() {
timePlayed.setText("Time: " + gameTimeCount + " ...
}
private void updateShotsFired() {
shotAccuracy = (shotsHit / shotsFired) * 100;
bulletsFired.setText("Bullets Fired: " + shotsFi...
bulletsHit.setText("Bullets Hit: " + shotsHit);
accuracy.setText("Accuracy: " + shotAccuracy + "...
targetsDestroyed.setText("Targets Destroyed: " +...
pointSum.setText("Points: " + points);
}
// Set the text on the gui display
public void updateWeaponDisplay() {
if (weaponState == 0) {
selectedWeapon.setText("Laser Beam");
} else if (weaponState == 1) {
selectedWeapon.setText("Cannon Ball");
} else {
selectedWeapon.setText("Arrow");
}
}
private void createNewCubes(String hit) {
if (hit.equals("Ball 1")) {
ball1++;
if (ball1 == 1) {
shootables.detachChildNamed(hit);
objectExplodeAudio.playInstance();
target.createBall1();
points = points + 2;
destroyedTarget++;
ball1 = 0;
}
} else if (hit.equals("Ball 2")) {
ball2++;
if (ball2 == 2) {
shootables.detachChildNamed(hit);
objectExplodeAudio.playInstance();
target.createBall2();
points = points + 6;
destroyedTarget++;
ball2 = 0;
}
} else if (hit.equals("Ball 3")) {
ball3++;
if (ball3 == 3) {
shootables.detachChildNamed(hit);
objectExplodeAudio.playInstance();
target.createBall3();
points = points + 10;
destroyedTarget++;
ball3 = 0;
}
} else if (hit.equals("Ball 4")) {
ball4++;
if (ball4 == 4) {
shootables.detachChildNamed(hit);
objectExplodeAudio.playInstance();
target.createBall4();
points = points + 16;
destroyedTarget++;
ball4 = 0;
}
}
}
}
- [[YouTube Video:https://www.youtube.com/watch?v=agwQ4_n...
- Document
#ref(CMSC325_FinalProject.pdf)
終了行:
#contents
** Week 1 Participation Topic: Personal Experience [#i5e0...
- Question
Please reply to this topic with your background in gaming.
Specify your first experience of gaming and the game syst...
What game system do you currently own/use, including cons...
What is your favorite game and game type? Why do you like...
Lastly, please outline your future career plan in gaming ...
- Answer
''Specify your first experience of gaming and the game sy...
My first game console I ever used was Nintendo Family Com...
Also my first mobile device I used was Game Boy, and what...
''What game system do you currently own/use, including co...
Game systems I currently own are as follows.
Consoles: PlayStation, PlayStation 2~
Mobile devices: Game Boy Light, Android Phone, iPhone 5~
Mac: iBook G4, Macbook
''What is your favorite game and game type? Why do you li...
Role-playing Games (RPGs) are the most favorite because i...
In addition to RPGs, I also like simulation games. I ofte...
''Lastly, please outline your future career plan in gamin...
In my future, I am interested in working for creating soc...
** Week 1 Homework 1 [#j0cada60]
- Question
Your task for this first homework assignment is to instal...
What to submit:
-- All the source code for your game.
-- A compiled JAR or executable file.
-- A text file briefly describing how to run and play you...
All of the above should be attached to your assignment as...
- Answer
- CoinFlipTest.java
import java.util.*;
import javax.swing.*;
public class CoinFlipTest {
public static void main(String[] args) {
int select, rand, result;
String selectvalues[] = {"Heads", "Tails"};
String coinSides=null, userGuess=null;
/** Instantiate an array list for storing outcomes. **/
ArrayList<Integer> outcomes = new ArrayList<Integer>();
for (int i=0; i<100; i++) { // Determine the number of...
/** Flip the coin, and then it comes up heads or tail...
rand = generateRandomValue();
if (rand == 0) {
coinSides = "Heads";
} else {
coinSides = "Tails";
}
/** User selection **/
int j = i + 1;
select = JOptionPane.showOptionDialog(null,
"Choose Heads or Tails. " + "(Number of times: " + ...
"Your Guess",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
selectvalues,
selectvalues[0]);
// if user click on the close button, break out of th...
if (select == JOptionPane.CLOSED_OPTION) {
break;
}
/** Determine if user guess is right or wrong. **/
if (rand == select) {
userGuess = "right";
outcomes.add(0); // if right => 0
} else {
userGuess = "wrong";
outcomes.add(1); // if wrong => 1
}
/** Display a result. **/
JOptionPane.showMessageDialog(null,
"The result is " + coinSides + "! " + "Your guess i...
"Result",
JOptionPane.INFORMATION_MESSAGE);
}
/** Display the odds **/
JOptionPane.showMessageDialog(null,
"Your odds of getting the right guess are " + calcul...
"Your Odds",
JOptionPane.INFORMATION_MESSAGE);
}
/** Generate a random value for flip of a coin. **/
private static int generateRandomValue() {
int r = (int) (Math.random()*2);
return r;
}
/** Calculate user odds. **/
private static float calculateOdds(ArrayList<Integer> l...
int numOfRightAnswers=0, numOfWrongAnswers=0;
Iterator it = list.iterator();
while(it.hasNext()) {
Integer e = (Integer) (it.next());
if (e == 0) {
numOfRightAnswers++;
} else {
numOfWrongAnswers++;
}
}
// odds = the number of desirable outcomes/the number ...
return (float) numOfRightAnswers/numOfWrongAnswers;
}
}
** Week 2 Participation Topic: Storytelling in Games [#dd...
- Question
Pick a story-driven game that you have recently played. S...
Describe what the game was, what captivated you about the...
If you cannot think of any games for your story-telling, ...
- Answer
One of the best story-driven games that I ever played was...
The story is set in 1964 after the Cuban Missile Crisis i...
In addition to its splendid story, its 3D depiction makes...
** Week 2 Homework 2 [#rdf9b39b]
- Question
Within 500 words, describe the social implications of gam...
As with all written assignments, please review your paper...
- Answer
#ref(CMSC325_Homework2.pdf)
** Week 3 Project 1: Questions and Comments [#a32901fe]
- My Question
I am wondering which I should choose Java or C++ as my la...
Hopefully I would like to use OpenGL with C++ because I t...
Can I submit only header files and source codes? Or, do I...
What do you recommend?
- Professor's answer
I would recommend you to use JMonkey 3d engine, which is ...
Just go over the tutorials to get started.
** Week 3 Project 1 [#f4c3448b]
- Question
You will use an existing game engine and map to modify an...
The level you create must be unique, realistic and playab...
''The following components and design criteria should be ...
-- Any code borrowed from other sources and sites must be...
-- A comprehensive test suite should be used and document...
''Deliverables include:''
-- All source code
-- Compile and run instructions
-- Test suite data and description along with output resu...
- BouncingBallsMain.java
import com.jme3.app.SimpleApplication;
import com.jme3.bullet.BulletAppState;
import com.jme3.bullet.control.RigidBodyControl;
import com.jme3.collision.CollisionResult;
import com.jme3.collision.CollisionResults;
import com.jme3.font.BitmapText;
import com.jme3.input.MouseInput;
import com.jme3.input.controls.ActionListener;
import com.jme3.input.controls.MouseButtonTrigger;
import com.jme3.material.Material;
import com.jme3.material.RenderState.BlendMode;
import com.jme3.math.ColorRGBA;
import com.jme3.math.Ray;
import com.jme3.math.Vector3f;
import com.jme3.renderer.queue.RenderQueue;
import com.jme3.scene.Geometry;
import com.jme3.scene.Node;
import com.jme3.scene.shape.Box;
import com.jme3.scene.shape.Sphere;
import java.util.ArrayList;
/**
* @author yujishimojo
*/
public class BouncingBallsMain extends SimpleApplication {
public static void main(String args[]) {
BouncingBallsMain app = new BouncingBallsMain();
app.start();
}
/** Prepare the Physics Application State (jBullet) */
private BulletAppState bulletAppState;
/** Prepare Materials */
Material ball_mat, floor_mat, red_wall_mat, blue_wall_...
green_wall_mat, yellow_wall_mat;
/** Prepare geometries and physical nodes for walls an...
private RigidBodyControl ball_phy, floor_phy, red_w...
blue_wall_phy, green_wall_...
private static final Sphere sphere;
private static final Box floor, red_wall, blue_wall...
private static Node shootables;
private static Geometry ball_geo, floor_geo, red_wall_...
green_wall_geo, yellow_wall_ge...
private static ArrayList list1, list2;
static {
/** Initialize the ball geometry */
sphere = new Sphere(32, 32, 0.4f, true, false);
/** Initialize the floor geometry */
floor = new Box(Vector3f.ZERO, 5f, 0.1f, 5f);
/** Initialize the walls geometry */
red_wall = new Box(Vector3f.ZERO, 5f, 5f, 0.1f);
blue_wall = new Box(Vector3f.ZERO, 5f, 5f, 0.1f);
green_wall = new Box(Vector3f.ZERO, 0.1f, 5f, 5f);
yellow_wall = new Box(Vector3f.ZERO, 0.1f, 5f, 5f);
list1 = new ArrayList();
list2 = new ArrayList();
}
@Override
public void simpleInitApp() {
/** Set up Physics Game */
bulletAppState = new BulletAppState();
stateManager.attach(bulletAppState);
// This array is used to decide camera location
float[] array = generateRandomLocation();
/** Configure cam to look at scene */
// Cam location and direction will be selected rando...
cam.setLocation(new Vector3f(array[0], 20f, array[1]...
cam.lookAt(new Vector3f(array[2], 10, array[3]), Vec...
/** Add InputManager action: Left click triggers sho...
inputManager.addMapping("shoot",
new MouseButtonTrigger(MouseInput.BUTTON_LEF...
inputManager.addListener(actionListener, "shoot");
/** Initialize the scene, materials, and physics spa...
initMaterials();
initFloor();
initRedWall();
initBlueWall();
initGreenWall();
initYellowWall();
initCrossHairs();
/** create a floor and four walls to shoot at: */
shootables = new Node("Shootables");
rootNode.attachChild(shootables);
shootables.attachChild(floor_geo);
shootables.attachChild(red_wall_geo);
shootables.attachChild(blue_wall_geo);
shootables.attachChild(green_wall_geo);
shootables.attachChild(yellow_wall_geo);
}
/**
* Every time the shoot action is triggered, a new bal...
* The ball is set up to fly from the camera position ...
*/
private ActionListener actionListener = new ActionList...
public void onAction(String name, boolean keyPressed...
initCrossHairs();
if (name.equals("shoot") && !keyPressed) {
makeBall();
// Reset results list.
CollisionResults results = new CollisionResults();
// Aim the ray from cam loc to cam direction.
Ray ray = new Ray(cam.getLocation(), cam.getDire...
// Collect intersections between Ray and Shootab...
shootables.collideWith(ray, results);
// Print the results
for (int i = 0; i < results.size(); i++) {
float dist = results.getCollision(i).getDistan...
Vector3f pt = results.getCollision(i).getConta...
String hit = results.getCollision(i).getGeomet...
// Display a position of a shpere on collision
// For each hit, we know distance, impact poin...
guiNode.detachAllChildren();
guiFont = assetManager.loadFont("Interface/Fon...
BitmapText text = new BitmapText(guiFont, fals...
text.setSize(guiFont.getCharSet().getRenderedS...
text.setText("Ball hits " + hit + " at " + pt);
text.setLocalTranslation(250, text.getLineHeig...
guiNode.attachChild(text);
// Store 3D vector positions to an array list ...
list1.add(pt);
System.out.println("(x, y, z) = " + list1);
}
if (results.size() > 0) {
CollisionResult closest = results.getClosest...
ball_geo.setLocalTranslation(closest.getCont...
rootNode.attachChild(ball_geo);
} else {
rootNode.detachChild(ball_geo);
}
}
}
};
/** Initialize the materials used in this scene. */
public void initMaterials() {
ball_mat = new Material(assetManager, "Common/MatDef...
ball_mat.setColor("Color", new ColorRGBA(0.4f,0,0.2f...
floor_mat = new Material(assetManager, "Common/MatDe...
floor_mat.setColor("Color", new ColorRGBA(0.6f,0.3f,...
//floor_mat.getAdditionalRenderState().setBlendMode(...
red_wall_mat = new Material(assetManager, "Common/Ma...
red_wall_mat.setColor("Color", new ColorRGBA(0.5f,0f...
//red_wall_mat.getAdditionalRenderState().setBlendMo...
blue_wall_mat = new Material(assetManager, "Common/M...
blue_wall_mat.setColor("Color", new ColorRGBA(0f,0f,...
//blue_wall_mat.getAdditionalRenderState().setBlendM...
green_wall_mat = new Material(assetManager, "Common/...
green_wall_mat.setColor("Color", new ColorRGBA(0f,0....
//green_wall_mat.getAdditionalRenderState().setBlend...
yellow_wall_mat = new Material(assetManager, "Common...
yellow_wall_mat.setColor("Color", new ColorRGBA(0.5f...
//yellow_wall_mat.getAdditionalRenderState().setBlen...
}
/** Make a solid floor. */
public void initFloor() {
floor_geo = new Geometry("floor", floor);
floor_geo.setMaterial(floor_mat);
//make the floor translucent
floor_geo.setQueueBucket(RenderQueue.Bucket.Transluc...
floor_geo.setLocalTranslation(0, 1, 0);
this.rootNode.attachChild(floor_geo);
/* Make the floor physical with mass 0.0f! */
floor_phy = new RigidBodyControl(0.0f);
floor_geo.addControl(floor_phy);
bulletAppState.getPhysicsSpace().add(floor_phy);
}
/** Make solid walls. */
public void initRedWall() {
red_wall_geo = new Geometry("red wall", red_wall);
red_wall_geo.setMaterial(red_wall_mat);
//make the wall translucent
red_wall_geo.setQueueBucket(RenderQueue.Bucket.Trans...
red_wall_geo.setLocalTranslation(0, 5.9f, 5.1f);
this.rootNode.attachChild(red_wall_geo);
/* Make the wall physical with mass 0.0f! */
red_wall_phy = new RigidBodyControl(0.0f);
red_wall_geo.addControl(red_wall_phy);
bulletAppState.getPhysicsSpace().add(red_wall_phy);
}
public void initBlueWall() {
blue_wall_geo = new Geometry("blue wall", blue_wall);
blue_wall_geo.setMaterial(blue_wall_mat);
//make the wall translucent
blue_wall_geo.setQueueBucket(RenderQueue.Bucket.Tran...
blue_wall_geo.setLocalTranslation(0, 5.9f, -5.1f);
this.rootNode.attachChild(blue_wall_geo);
blue_wall_phy = new RigidBodyControl(0.0f);
blue_wall_geo.addControl(blue_wall_phy);
bulletAppState.getPhysicsSpace().add(blue_wall_phy);
}
public void initGreenWall() {
green_wall_geo = new Geometry("green wall", green_wa...
green_wall_geo.setMaterial(green_wall_mat);
//make the wall translucent
green_wall_geo.setQueueBucket(RenderQueue.Bucket.Tra...
green_wall_geo.setLocalTranslation(-5.1f, 5.9f, 0);
this.rootNode.attachChild(green_wall_geo);
green_wall_phy = new RigidBodyControl(0.0f);
green_wall_geo.addControl(green_wall_phy);
bulletAppState.getPhysicsSpace().add(green_wall_phy);
}
public void initYellowWall() {
yellow_wall_geo = new Geometry("yellow wall", yellow...
yellow_wall_geo.setMaterial(yellow_wall_mat);
//make the wall translucent
yellow_wall_geo.setQueueBucket(RenderQueue.Bucket.Tr...
yellow_wall_geo.setLocalTranslation(5.1f, 5.9f, 0);
this.rootNode.attachChild(yellow_wall_geo);
yellow_wall_phy = new RigidBodyControl(0.0f);
yellow_wall_geo.addControl(yellow_wall_phy);
bulletAppState.getPhysicsSpace().add(yellow_wall_phy);
}
/** This method creates one individual physical ball.
* The ball is accelerated and flies
* from the camera position in the camera direction.*/
public void makeBall() {
/** Create a ball geometry. */
ball_geo = new Geometry("ball", sphere);
ball_geo.setMaterial(ball_mat);
shootables.attachChild(ball_geo);
/** Position the ball */
ball_geo.setLocalTranslation(cam.getLocation());
/** Make the ball physcial with a mass > 0.0f */
ball_phy = new RigidBodyControl(1f);
/** Add physical ball to physics space. */
ball_geo.addControl(ball_phy);
bulletAppState.getPhysicsSpace().add(ball_phy);
/** Accelerate the physcial ball to shoot it. */
int velocity = generateRandomVelocity();
ball_phy.setLinearVelocity(cam.getDirection().mult(v...
// Store linear velocities to an array list and show...
list2.add(velocity);
System.out.println("Velocity is " + list2);
/** Set gravity on y-axis. */
ball_phy.setGravity(new Vector3f(0, -5, 0));
}
/** Generate a random velocity from 20 to 80. **/
private int generateRandomVelocity() {
int v = (int) Math.ceil(Math.random()*61)+20;
return v;
}
/** Generate a random camera location between 4. **/
private float[] generateRandomLocation() {
float[] a0 = {5f, 10f, 1f, -1f};
float[] a1 = {10f, -10f, -1f, -1f};
float[] a2 = {-5f, -10f, -1f, 1f};
float[] a3 = {-10f, 5f, 1f, 1f};
int n = (int) Math.floor(Math.random()*4);
switch (n) {
case 0: return a0;
case 1: return a1;
case 2: return a2;
case 3: return a3;
default: return a0;
}
}
/** A plus sign used as crosshairs to help the playe...
protected void initCrossHairs() {
guiNode.detachAllChildren();
guiFont = assetManager.loadFont("Interface/Fonts...
BitmapText ch = new BitmapText(guiFont, false);
ch.setSize(guiFont.getCharSet().getRenderedSize(...
ch.setText("+"); // fake crosshairs :)
ch.setLocalTranslation( // center
settings.getWidth() / 2 - guiFont.getCharSet...
settings.getHeight() / 2 + ch.getLineHeight(...
guiNode.attachChild(ch);
}
}
- [[YouTube Video:https://www.youtube.com/watch?v=vZqhPRf...
** Week 4 Participation Topic: Painting with Triangles [#...
- Question
Since the advent of polygons to draw game objects and mov...
- Answer
Metal Gear Solid series are definitely suited for 3D poly...
- Respond to Joel Braun
I agree with the point that the positioning would be easi...
In fighting games, it is important for users to be able t...
- Respond to Xuefen Li
I agree that Super Mario Bros. is a successful example to...
I think such migration of this kind of game is quite a ha...
** Week 4 Homework 3 [#rd4e0ea7]
- Question
The conference discussion this week will have you looking...
As with all written assignments, please review your paper...
- Answer
#ref(CMSC325_Homework3.pdf)
** Week 5 Participation Topic: Acting Out [#fde4fa05]
- Question
When you think about artificial intelligence, you might i...
This week, I would like everyone to think about and descr...
- Answer
An example of non-traditional AI based game I ever played...
You run your own pro soccer club by making training progr...
Sorry! I could find the only Japanese Web site as below.~
http://www.sakatsuku.com/history/06/
** Week 5 Homework 4 [#z6e2444c]
- Question
Especially with online multiplayer games, companies are h...
As with all written assignments, please review your paper...
- Answer
#ref(CMSC325_Homework4.pdf)
** Week 6 Finding Your Own Path [#cea499f4]
- Question
As you should all have realized by now, designing and mak...
This week, I want to know what you had to go searching fo...
- Answer
I created both PR1 and PR2 by using jMonkeyEngine for the...
http://jmonkeyengine.org/wiki/doku.php/jme3
Sometimes, I can hardly understand of exact behavior and ...
http://www.jmonkeyengine.com/doc/
Because jME org offers a lot of materials, I can find out...
** Week 6 Project 2 [#cd8eb041]
- Question
Create a Java or C# application that simulates a minimum ...
You should submit your completed application Java source ...
''Deliverables include:''
-- All source code
-- Compile and run instructions
-- Test suite data and description along with output resu...
- BouncingBallsMain2.java
import com.jme3.app.SimpleApplication;
import com.jme3.bullet.BulletAppState;
import com.jme3.bullet.collision.PhysicsCollisionEvent;
import com.jme3.bullet.collision.PhysicsCollisionListener;
import com.jme3.bullet.control.RigidBodyControl;
import com.jme3.collision.CollisionResults;
import com.jme3.font.BitmapText;
import com.jme3.input.KeyInput;
import com.jme3.input.controls.ActionListener;
import com.jme3.input.controls.KeyTrigger;
import com.jme3.material.Material;
import com.jme3.material.RenderState.BlendMode;
import com.jme3.math.ColorRGBA;
import com.jme3.math.Ray;
import com.jme3.math.Vector2f;
import com.jme3.math.Vector3f;
import com.jme3.renderer.queue.RenderQueue.Bucket;
import com.jme3.scene.Geometry;
import com.jme3.scene.shape.Box;
import com.jme3.scene.shape.Sphere;
import java.util.Random;
/**
* @author yujishimojo
*/
public class BouncingBallsMain2 extends SimpleApplicatio...
public static BouncingBallsMain2 app = new BouncingB...
//create a new file for storing position and velocit...
public static java.io.File file = new java.io.File("...
public static java.io.PrintWriter output;
public static java.io.File file2 = new java.io.File(...
public static java.io.PrintWriter output2;
// initiate the objects for generating random numbers
private Random positionGenerator = new Random();
private Random velGenerator = new Random();
private Random posNegGenerator = new Random();
private Random gravGenerator = new Random();
private Vector3f pt; // 3D vector position of bal...
private String hit; // which the object ball hits
// intiate the variable for storing time
long startTime;
long startGravTime;
long estimatedTime;
// variable determines whether gravity is universal
// or seperate for the balls
boolean randGrav = false;
private BitmapText gravText;
// Set the number of generated balls
final int NUMBALLS = 8;
// Set the initial velocity in XYZ
final int IVX = 5;
final int IVY = 5;
final int IVZ = 5;
// intiate the objects that will allow for the appli...
private BulletAppState bulletAppState;
private RigidBodyControl[] ball_physics = new RigidB...
BouncingBallsMain2.BallTextDisplay[] ballDisplays = ...
public static void main(String[] args) throws Except...
output = new java.io.PrintWriter(file);
output2 = new java.io.PrintWriter(file2);
app.start(); // start the game
}
@Override
public void simpleInitApp() {
bulletAppState = new BulletAppState();
stateManager.attach(bulletAppState);
bulletAppState.getPhysicsSpace().addCollisionLis...
// Set the location of the camera to be in one o...
// top corners of the cube looking in towards th...
cam.setLocation(new Vector3f(45, 40, 40));
cam.lookAt(new Vector3f(0, 0, 0), Vector3f.UNIT_...
flyCam.setEnabled(true);
flyCam.setMoveSpeed(10);
// Start the timer
startTime = System.currentTimeMillis();
startGravTime = System.currentTimeMillis();
BouncingBallsMain2.SphereObj[] sphereObjects = n...
//Create the spheres
for (int i = 0; i < NUMBALLS; i++) {
if (i < 2) {
// posX: -15 to -10, posY: -3 to 2, posZ...
sphereObjects[i] = new BouncingBallsMain...
}
else if(i < 4) {
// posX: -5 to 0, posY: -3 to 2, posZ: -...
sphereObjects[i] = new BouncingBallsMain...
}
else if (i < 6) {
// posX: 5 to 10, posY: -3 to 2, posZ: -...
sphereObjects[i] = new BouncingBallsMain...
}
else {
// posX: 15 to 20, posY: -3 to 2, posZ: ...
sphereObjects[i] = new BouncingBallsMain...
}
}
// Give the balls a physical presence
for (int i = 0; i < NUMBALLS; i++) {
ball_physics[i] = new RigidBodyControl(1f);
}
// Add the balls to the scene
for (int i = 0; i < NUMBALLS; i++) {
sphereObjects[i].addControl(ball_physics[i]);
}
for (int i = 0; i < NUMBALLS; i++) {
bulletAppState.getPhysicsSpace().add(ball_ph...
}
// Make the balls bouncy
for (int i = 0; i < NUMBALLS; i++) {
ball_physics[i].setRestitution(1.5f);
}
// Add the fllor, walls, and ceiling to the scene
BouncingBallsMain2.WallObj floor1 = new Bouncing...
BouncingBallsMain2.WallObj floor2 = new Bouncing...
BouncingBallsMain2.WallObj floor3 = new Bouncing...
//BouncingBallsMain2.WallObj floor4 = new Bounci...
BouncingBallsMain2.WallObj floor4 = new Bouncing...
BouncingBallsMain2.WallObj floor5 = new Bouncing...
BouncingBallsMain2.WallObj floor6 = new Bouncing...
BouncingBallsMain2.WallObj floor7 = new Bouncing...
BouncingBallsMain2.WallObj wall1 = new BouncingB...
BouncingBallsMain2.WallObj wall1_1 = new Bouncin...
BouncingBallsMain2.WallObj wall1_2 = new Bouncin...
BouncingBallsMain2.WallObj wall2 = new BouncingB...
BouncingBallsMain2.WallObj wall2_1 = new Bouncin...
BouncingBallsMain2.WallObj wall2_2 = new Bouncin...
BouncingBallsMain2.WallObj wall2_3 = new Bouncin...
BouncingBallsMain2.WallObj wall2_4 = new Bouncin...
BouncingBallsMain2.WallObj wall2_5 = new Bouncin...
BouncingBallsMain2.WallObj wall2_6 = new Bouncin...
BouncingBallsMain2.WallObj wall2_7 = new Bouncin...
BouncingBallsMain2.WallObj wall2_8 = new Bouncin...
BouncingBallsMain2.WallObj wall2_9 = new Bouncin...
BouncingBallsMain2.WallObj wall2_10 = new Bounci...
BouncingBallsMain2.WallObj wall2_11 = new Bounci...
BouncingBallsMain2.WallObj wall3 = new BouncingB...
BouncingBallsMain2.WallObj wall3_1 = new Bouncin...
BouncingBallsMain2.WallObj wall3_2 = new Bouncin...
BouncingBallsMain2.WallObj wall4 = new BouncingB...
BouncingBallsMain2.WallObj wall4_1 = new Bouncin...
BouncingBallsMain2.WallObj wall4_2 = new Bouncin...
BouncingBallsMain2.WallObj wall4_3 = new Bouncin...
BouncingBallsMain2.WallObj wall4_4 = new Bouncin...
BouncingBallsMain2.WallObj wall4_5 = new Bouncin...
BouncingBallsMain2.WallObj wall4_6 = new Bouncin...
BouncingBallsMain2.WallObj wall4_7 = new Bouncin...
BouncingBallsMain2.WallObj wall4_8 = new Bouncin...
BouncingBallsMain2.WallObj wall4_9 = new Bouncin...
BouncingBallsMain2.WallObj wall4_10 = new Bounci...
BouncingBallsMain2.WallObj wall4_11 = new Bounci...
BouncingBallsMain2.WallObj roof = new BouncingBa...
//BouncingBallsMain2.WallObj roof_1 = new Bounci...
BouncingBallsMain2.WallObj roof_1 = new Bouncing...
BouncingBallsMain2.WallObj roof_2 = new Bouncing...
BouncingBallsMain2.WallObj roof_3 = new Bouncing...
BouncingBallsMain2.WallObj roof_4 = new Bouncing...
BouncingBallsMain2.WallObj roof_5 = new Bouncing...
BouncingBallsMain2.WallObj roof_6 = new Bouncing...
// Generate the same gravity for all the balls
Vector3f worldGrav = generateRandomGravity();
// Set the gravity and random velocity to all th...
for (int i = 0; i < NUMBALLS; i++) {
if (randGrav) {
ball_physics[i].setGravity(generateRando...
}
else {
ball_physics[i].setGravity(worldGrav);
}
estimatedTime = System.currentTimeMillis() -...
// Set the initial velocity to all the balls
ball_physics[i].setLinearVelocity(new Vector...
if (estimatedTime > 500) {
// Set the random velocity to all the ba...
ball_physics[i].setLinearVelocity(genera...
}
}
// Remove the default text display from the gui.
guiNode.detachAllChildren();
setDisplayStatView(false);
setDisplayFps(false);
guiFont = assetManager.loadFont("Interface/Fonts...
// Add the text for tracking the balls' location...
for (int i = 0; i < NUMBALLS; i++) {
ballDisplays[i] = new BouncingBallsMain2.Bal...
}
gravText = new BitmapText(guiFont, false);
gravText.setSize(guiFont.getCharSet().getRendere...
if (randGrav) {
gravText.setText("Separate Gravity");
}
else {
gravText.setText("Universal Gravity");
}
gravText.setLocalTranslation(50, 50, 0);
guiNode.attachChild(gravText);
// Customize the keys
initKeys();
}
// Make it so that pressing P will exit the game
// If P is not used to exit the game, then the
// position and velocity data on the playthrough
// will not be saved and the text file will be
// blank
// Make it so that pressing G will switch gravity
// between universal and individual
public void initKeys() {
inputManager.addMapping("Exit", new KeyTrigger(...
inputManager.addListener(actionListener, new Str...
inputManager.addMapping("Gravity", new KeyTrigge...
inputManager.addListener(actionListener, new Str...
}
private ActionListener actionListener = new ActionLi...
public void onAction(String name, boolean keyPre...
if (name.equals("Exit") && !keyPressed) {
output.close();
output2.close();
app.stop();
}
if (name.equals("Gravity") && !keyPressed) {
randGrav = !randGrav;
}
}
};
// An event handler to detect collisions
public void collision(PhysicsCollisionEvent event) {
CollisionResults results = new CollisionResults();
Ray ray = new Ray(cam.getLocation(), cam.getDire...
rootNode.collideWith(ray, results); // detect...
if (results.size() > 0) {
for (int i = 0; i < results.size(); i++) {
pt = results.getCollision(i).getContactP...
hit = results.getCollision(i).getGeometr...
// ** Test code beginning
// output2.println(hit + ": " + pt);
output2.println(hit + " " + pt);
// ** Test code end
System.out.println("----- Collision # " ...
System.out.println("A ball hits " + hit ...
}
}
}
// The update loop for changing the text display in r...
// and for calling the method for recording positio...
// velocity, and gravity data on the current playth...
@Override
public void simpleUpdate(float tpf) {
estimatedTime = System.currentTimeMillis() - sta...
long estimatedGravTime = System.currentTimeMilli...
// Commented out below
/* System.out.println(estimatedTime + ", " + sta...
int elapsedTime = 0;
// if one second has elapsed in game
if(estimatedTime > 1000) {
// update the gui and record position and ve...
// to the text file
updatePositionDisplay();
for (int i = 0; i < NUMBALLS; i++) {
output.println("B" + i + ": " + getBallP...
}
startTime = System.currentTimeMillis();
}
// otherwise, only update the gui
else {
updatePositionDisplay();
}
// if at least 5 seconds has elapsed from the la...
// the gravity. If randGrav true, then each ball...
// gravity. Otherwise, change the world gravity.
if(estimatedGravTime > 5000) {
Vector3f worldGrav = generateRandomGravity();
for (int i = 0; i < NUMBALLS; i++) {
if (randGrav){
ball_physics[i].setGravity(generateR...
}
else {
ball_physics[i].setGravity(worldGrav);
}
}
startGravTime = System.currentTimeMillis();
}
}
// set the text on the gui display
public void updatePositionDisplay() {
for (int i = 0; i < NUMBALLS; i++) {
ballDisplays[i].setText(ball_physics[i]);
}
if (randGrav) {
gravText.setText("Separate Gravity");
}
else {
gravText.setText("Universal Gravity");
}
}
// generates a random velocity for a ball
public Vector3f generateRandomVelocity() {
float velx = velGenerator.nextInt(10);
int posNeg = posNegGenerator.nextInt(2);
if (posNeg == 0) {
velx *= -1;
}
float vely = velGenerator.nextInt(10);
posNeg = posNegGenerator.nextInt(2);
if (posNeg == 0) {
vely *= -1;
}
float velz = velGenerator.nextInt(10);
posNeg = posNegGenerator.nextInt(2);
if (posNeg == 0) {
velz *= -1;
}
return new Vector3f( velx , vely , velz );
}
// generates a random gravity for all of the balls
// or for each ball separately
public Vector3f generateRandomGravity() {
float gravX = gravGenerator.nextInt(3);
int posNeg = posNegGenerator.nextInt(2);
if (posNeg == 0) {
gravX *= -1;
}
float gravY = gravGenerator.nextInt(3);
posNeg = posNegGenerator.nextInt(2);
if (posNeg == 0) {
gravY *= -1;
}
float gravZ = gravGenerator.nextInt(3);
posNeg = posNegGenerator.nextInt(2);
if (posNeg == 0) {
gravZ *= -1;
}
return new Vector3f(gravX, gravY, gravZ);
}
// generates a random position
public int generateRandomPos() {
int pos = positionGenerator.nextInt(6);
return pos;
}
public String getBallPosString(RigidBodyControl ball...
String xPos = String.format("%5.2f", ball_physic...
String yPos = String.format("%5.2f", ball_physic...
String zPos = String.format("%5.2f", ball_physic...
// ** Test code beginning
// return "(" + xPos + ", " + yPos + ", " + zPos ...
return xPos + " " + yPos + " " + zPos;
// ** Test code end
}
// the sphere sphere object
public class SphereObj {
Vector3f position;
Sphere sphere;
Geometry geomSphere;
Material mat;
// constructor method that generates the sphere
SphereObj(String color, int minX) {
// the balls' radius are 0.5
sphere = new Sphere(32, 32, 0.5f);
geomSphere = new Geometry("Sphere", sphere);
mat = new Material(assetManager,
"Common/MatDefs/Misc/Unshaded.j3md");
if (color.equalsIgnoreCase("yellow")) {
mat.setColor("Color", ColorRGBA.Yellow);
} else if (color.equalsIgnoreCase("red")) {
mat.setColor("Color", ColorRGBA.Red);
} else if (color.equalsIgnoreCase("green")) {
mat.setColor("Color", ColorRGBA.Green);
} else {
mat.setColor("Color", new ColorRGBA(1, 0...
}
geomSphere.setMaterial(mat);
rootNode.attachChild(geomSphere);
int posX = minX + generateRandomPos();
int posY = -3 + generateRandomPos();
int posZ = -3 + generateRandomPos();
geomSphere.move(posX, posY, posZ);
}
// method that adds the physics aspects to the s...
public void addControl(RigidBodyControl ball_phy...
geomSphere.addControl(ball_phy);
}
}
// the wall class
public class WallObj {
Vector3f position;
Box box;
Geometry geomWall;
Material mat;
private RigidBodyControl phy;
// constructor that generates a wall object
// the parameters are the dimensions of the wall...
// and the translations the wall undergoes
WallObj(float x, float y, float z, String name, ...
box = new Box(Vector3f.ZERO, x, y, z);
box.scaleTextureCoordinates(new Vector2f(3, ...
geomWall = new Geometry(name, box);
mat = new Material(assetManager,
"Common/MatDefs/Misc/Unshaded.j3md");...
//set color of wall with alpha channel so ca...
if (color.equalsIgnoreCase("blue")) {
mat.setColor("Color", new ColorRGBA(0, 0...
} else if (color.equalsIgnoreCase("pink")) {
mat.setColor("Color", new ColorRGBA(1f, ...
} else if (color.equalsIgnoreCase("orange")) {
mat.setColor("Color", new ColorRGBA(.98f...
}
// make walls translucent
mat.getAdditionalRenderState().setBlendMode(...
geomWall.setMaterial(mat);
geomWall.setQueueBucket(Bucket.Translucent);
// move wall to position
geomWall.setLocalTranslation(xTrans, yTrans,...
rootNode.attachChild(geomWall);
phy = new RigidBodyControl(0.0f);
geomWall.addControl(phy);
bulletAppState.getPhysicsSpace().add(phy);
phy.setRestitution(0.5f);
}
// method that adds physics components to a wall
public void addControl(RigidBodyControl wall_phy...
geomWall.addControl(wall_phy);
}
}
// This class displays the text to the GUI
public class BallTextDisplay {
BitmapText ballText;
BitmapText gravText;
int ballNumber;
// This displays the positions of each ball sepa...
BallTextDisplay(int whichBall, float xPos, float...
ballText = new BitmapText(guiFont, false);
ballText.setSize(guiFont.getCharSet().getRe...
ballText.setText("B" + whichBall + ": ");
ballNumber = whichBall;
ballText.setLocalTranslation(xPos, yPos, zP...
guiNode.attachChild(ballText);
}
// This displays the positions of each ball sepa...
public void setText(RigidBodyControl ball_phy) {
String xPos = String.format("%5.2f", ball_phy...
String yPos = String.format("%5.2f", ball_phy...
String zPos = String.format("%5.2f", ball_phy...
ballText.setText("B" + ballNumber + ": (" + x...
}
}
}
- [[YouTube Video:https://www.youtube.com/watch?v=JSuMY9f...
- Test Data
#ref(BouncingBalls2TestData.pdf)
** Week 7 Social Anxiety [#x9b258fc]
- Question
A social gaming. Like it or hate it, it is one of the maj...
- Answer
From the view point of an user, I like the trend. You can...
From the view point of a social game provider, social gam...
It is harder to make users lock in a specific platform be...
The business model was drastically changed. Prices of a g...
** Week 8 Sequels [#a371cc26]
- Question
While networking and multiplayer aspects were not require...
What kind of game would you develop for this course? Woul...
- Answer
Because I am interested in more infrastructure side such ...
Since I learned 3D Java game programming using jMonkeyEng...
** Week 8 Final Project [#q7e618c2]
Students will use a popular, freely distributed game plat...
''Requirements:''
Using the 3D graphics and associated Physics engine devel...
+ At least 4 types of targets should be displayed in the ...
+ Each of the targets should be moving in the scene.
+ At least one of the targets should have gravity/physics...
+ Bullets or missiles should be unlimited.
+ A Heads-up Display should be provided with a minimum of...
+ High score should be stored in an ASCII file. Optionall...
+ Simple directions for running the game should be includ...
+ A game timer should be embedded limiting a game session...
+ Coding conventions should be followed based on the prog...
''Deliverables include:''
-- All source code in winzip format
-- Compile and run instructions
-- Well-written word document describing:
--- Your overall design
--- Your test plan, including test data and results
--- Your approach, lessons learned, design strengths, lim...
- Target.java
import com.jme3.asset.AssetManager;
import com.jme3.bullet.BulletAppState;
import com.jme3.bullet.control.RigidBodyControl;
import com.jme3.material.Material;
import com.jme3.math.ColorRGBA;
import com.jme3.scene.Geometry;
import com.jme3.scene.Node;
import com.jme3.scene.shape.Sphere;
import java.util.Random;
/*
* This class creates shootable objects made of four sph...
* The colors and locations of each sphere are randomly ...
* @author yujishimojo
*/
public final class Target {
private BulletAppState bulletAppState;
private Node rootNode;
private Node shootables;
private AssetManager assetManager;
public Geometry outlineBall1;
public Geometry outlineBall2;
public Geometry outlineBall3;
public Geometry outlineBall4;
public RigidBodyControl ballCollision1;
public RigidBodyControl ballCollision2;
public RigidBodyControl ballCollision3;
public RigidBodyControl ballCollision4;;
public Target (AssetManager assetManager, Node rootN...
this.bulletAppState = bulletAppState;
this.rootNode = rootNode;
this.shootables = shootables;
this.assetManager = assetManager;
rootNode.attachChild(shootables);
// Creates balls
createBall1();
createBall2();
createBall3();
createBall4();
}
public void createBall1() {
Random random = new Random();
Sphere createBall = new Sphere(32, 32, 0.8f);
outlineBall1 = new Geometry("Ball 1", createBall);
createBall.setTextureMode(Sphere.TextureMode.Pro...
Material mat = new Material(assetManager,
"Common/MatDefs/Misc/Unshaded.j3md");
mat.setColor("Color", ColorRGBA.randomColor());
outlineBall1.setMaterial(mat);
outlineBall1.setLocalTranslation((random.nextFlo...
shootables.attachChild(outlineBall1);
ballCollision1 = new RigidBodyControl(1f);
outlineBall1.addControl(ballCollision1);
bulletAppState.getPhysicsSpace().add(ballCollisi...
ballCollision1.setMass(1);
ballCollision1.setFriction(0);
ballCollision1.setRestitution(1.0f);
}
public void createBall2() {
Random random = new Random();
Sphere createBall = new Sphere(32, 32, 0.6f);
outlineBall2 = new Geometry("Ball 2", createBall);
createBall.setTextureMode(Sphere.TextureMode.Pro...
Material mat = new Material(assetManager,
"Common/MatDefs/Misc/Unshaded.j3md");
mat.setColor("Color", ColorRGBA.randomColor());
outlineBall2.setMaterial(mat);
outlineBall2.setLocalTranslation((random.nextFlo...
shootables.attachChild(outlineBall2);
ballCollision2 = new RigidBodyControl(1f);
outlineBall2.addControl(ballCollision2);
bulletAppState.getPhysicsSpace().add(ballCollisi...
ballCollision2.setMass(1);
ballCollision2.setFriction(0);
ballCollision2.setRestitution(1.0f);
}
public void createBall3() {
Random random = new Random();
Sphere createBall = new Sphere(32, 32, 0.4f);
outlineBall3 = new Geometry("Ball 3", createBall);
createBall.setTextureMode(Sphere.TextureMode.Pro...
Material mat = new Material(assetManager,
"Common/MatDefs/Misc/Unshaded.j3md");
mat.setColor("Color", ColorRGBA.randomColor());
outlineBall3.setMaterial(mat);
outlineBall3.setLocalTranslation((random.nextFlo...
shootables.attachChild(outlineBall3);
ballCollision3 = new RigidBodyControl(1f);
outlineBall3.addControl(ballCollision3);
bulletAppState.getPhysicsSpace().add(ballCollisi...
ballCollision3.setMass(1);
ballCollision3.setFriction(0);
ballCollision3.setRestitution(1.0f);
}
public void createBall4() {
Random random = new Random();
Sphere createBall = new Sphere(32, 32, 0.2f);
outlineBall4 = new Geometry("Ball 4", createBall);
createBall.setTextureMode(Sphere.TextureMode.Pro...
Material mat = new Material(assetManager,
"Common/MatDefs/Misc/Unshaded.j3md");
mat.setColor("Color", ColorRGBA.randomColor());
outlineBall4.setMaterial(mat);
outlineBall4.setLocalTranslation((random.nextFlo...
shootables.attachChild(outlineBall4);
ballCollision4 = new RigidBodyControl(1f);
outlineBall4.addControl(ballCollision4);
bulletAppState.getPhysicsSpace().add(ballCollisi...
ballCollision4.setMass(1);
ballCollision4.setFriction(0);
ballCollision4.setRestitution(1.0f);
}
}
- Cube.java
import com.jme3.asset.AssetManager;
import com.jme3.bullet.BulletAppState;
import com.jme3.bullet.control.RigidBodyControl;
import com.jme3.material.Material;
import com.jme3.material.RenderState;
import com.jme3.math.ColorRGBA;
import com.jme3.math.FastMath;
import com.jme3.math.Quaternion;
import com.jme3.math.Vector2f;
import com.jme3.math.Vector3f;
import com.jme3.scene.Geometry;
import com.jme3.scene.Mesh;
import com.jme3.scene.Node;
import com.jme3.scene.VertexBuffer;
import com.jme3.util.BufferUtils;
/*
* This class creates cubic scene objects made of six si...
* @author yujishimojo
*/
public class Cube {
private BulletAppState bulletAppState;
private Node rootNode;
private AssetManager assetManager;
public Cube (AssetManager assetManager, Node rootNod...
this.bulletAppState = bulletAppState;
this.rootNode = rootNode;
this.assetManager = assetManager;
// Create back side of cube
createBackCube();
// Create front side of cube
createFrontCube();
// Create right side of cube
createRightSideCube();
// Create left side of cube
createLeftSideCube();
// Create bottom side of cube
createBottomSideCube();
// Create top side of cube
createTopSideCube();
}
private void createBackCube() {
Mesh back = new Mesh();
// Back Wall
Vector3f[] backVertices = new Vector3f[4];
backVertices[0] = new Vector3f(0, 0, 0);
backVertices[1] = new Vector3f(9, 0, 0);
backVertices[2] = new Vector3f(0, 9, 0);
backVertices[3] = new Vector3f(9, 9, 0);
// Back Wall
Vector2f[] backCoord = new Vector2f[4];
backCoord[0] = new Vector2f(0, 0);
backCoord[1] = new Vector2f(1, 0);
backCoord[2] = new Vector2f(0, 1);
backCoord[3] = new Vector2f(1, 1);
// Indexes. We define the order in which mesh sh...
int[] indexes = {2, 0, 1, 1, 3, 2};
// Setting buffers
back.setBuffer(VertexBuffer.Type.Position, 3, Bu...
back.setBuffer(VertexBuffer.Type.TexCoord, 2, Bu...
back.setBuffer(VertexBuffer.Type.Index, 1, Buffe...
back.updateBound();
// Create back of cube
Geometry backGeom = new Geometry("OurMesh", back);
Material backMat = new Material(assetManager, "C...
backMat.setColor("Color", ColorRGBA.White);
backGeom.setMaterial(backMat);
backMat.getAdditionalRenderState().setWireframe(...
backMat.getAdditionalRenderState().setFaceCullMo...
rootNode.attachChild(backGeom);
RigidBodyControl backWallCollision = new RigidBo...
backGeom.addControl(backWallCollision);
bulletAppState.getPhysicsSpace().add(backWallCol...
backWallCollision.setRestitution(0.15f);
backWallCollision.setFriction(0);
}
private void createFrontCube() {
Mesh front = new Mesh();
// Front Wall
Vector3f[] frontVertices = new Vector3f[4];
frontVertices[0] = new Vector3f(0, 0, 9);
frontVertices[1] = new Vector3f(9, 0, 9);
frontVertices[2] = new Vector3f(0, 9, 9);
frontVertices[3] = new Vector3f(9, 9, 9);
// Front Wall
Vector2f[] frontCoord = new Vector2f[4];
frontCoord[0] = new Vector2f(0, 0);
frontCoord[1] = new Vector2f(1, 0);
frontCoord[2] = new Vector2f(0, 1);
frontCoord[3] = new Vector2f(1, 1);
// Indexes. We define the order in which mesh sh...
int[] indexes = {2, 0, 1, 1, 3, 2};
// Setting buffers
front.setBuffer(VertexBuffer.Type.Position, 3, B...
front.setBuffer(VertexBuffer.Type.TexCoord, 2, B...
front.setBuffer(VertexBuffer.Type.Index, 1, Buff...
front.updateBound();
// Create front of cube
Geometry frontGeom = new Geometry("OurMesh", fro...
Material frontMat = new Material(assetManager, "...
frontGeom.setMaterial(frontMat);
frontMat.setTransparent(true);
frontMat.getAdditionalRenderState().setFaceCullM...
rootNode.attachChild(frontGeom);
RigidBodyControl frontWallCollision = new RigidB...
frontGeom.addControl(frontWallCollision);
bulletAppState.getPhysicsSpace().add(frontWallCo...
frontWallCollision.setRestitution(0.15f);
frontWallCollision.setFriction(0);
}
private void createRightSideCube() {
Mesh rightSide = new Mesh();
Quaternion quatA = new Quaternion();
quatA.fromAngleAxis(-FastMath.HALF_PI, Vector3f....
// Right Wall
Vector3f[] rightSideVertices = new Vector3f[4];
rightSideVertices[0] = new Vector3f(3, 0, -9);
rightSideVertices[1] = new Vector3f(12, 0, -9);
rightSideVertices[2] = new Vector3f(3, 9, -9);
rightSideVertices[3] = new Vector3f(12, 9, -9);
Vector3f vectorA = quatA.mult(rightSideVertices[...
Vector3f vectorB = quatA.mult(rightSideVertices[...
Vector3f vectorC = quatA.mult(rightSideVertices[...
Vector3f vectorD = quatA.mult(rightSideVertices[...
Vector3f[] rightSideYes = new Vector3f[4];
rightSideYes[0] = new Vector3f(vectorA);
rightSideYes[1] = new Vector3f(vectorB);
rightSideYes[2] = new Vector3f(vectorC);
rightSideYes[3] = new Vector3f(vectorD);
// Right Wall
Vector2f[] rightSideCoord = new Vector2f[4];
rightSideCoord[0] = new Vector2f(0, 0);
rightSideCoord[1] = new Vector2f(1, 0);
rightSideCoord[2] = new Vector2f(0, 1);
rightSideCoord[3] = new Vector2f(1, 1);
// Indexes. We define the order in which mesh sh...
int[] indexes = {2, 0, 1, 1, 3, 2};
// Setting buffers
rightSide.setBuffer(VertexBuffer.Type.Position, ...
rightSide.setBuffer(VertexBuffer.Type.TexCoord, ...
rightSide.setBuffer(VertexBuffer.Type.Index, 1, ...
rightSide.updateBound();
// Create Right of cube
Geometry rightSideGeom = new Geometry("OurMesh",...
rightSideGeom.setLocalTranslation(0, 0, -3);
Material rightSideMat = new Material(assetManage...
rightSideMat.setColor("Color", ColorRGBA.White);
rightSideGeom.setMaterial(rightSideMat);
rightSideMat.getAdditionalRenderState().setWiref...
rightSideMat.getAdditionalRenderState().setFaceC...
RigidBodyControl rightWallCollision = new RigidB...
rightSideGeom.addControl(rightWallCollision);
bulletAppState.getPhysicsSpace().add(rightWallCo...
rightWallCollision.setRestitution(0.15f);
rightWallCollision.setFriction(0);
rootNode.attachChild(rightSideGeom);
}
private void createLeftSideCube() {
Mesh leftSide = new Mesh();
Quaternion quatA = new Quaternion();
quatA.fromAngleAxis(-FastMath.HALF_PI, Vector3f....
// Left Wall
Vector3f[] leftSideVertices = new Vector3f[4];
leftSideVertices[0] = new Vector3f(6, 0, 0);
leftSideVertices[1] = new Vector3f(-3, 0, 0);
leftSideVertices[2] = new Vector3f(6, 9, 0);
leftSideVertices[3] = new Vector3f(-3, 9, 0);
Vector3f vectorA = quatA.mult(leftSideVertices[0...
Vector3f vectorB = quatA.mult(leftSideVertices[1...
Vector3f vectorC = quatA.mult(leftSideVertices[2...
Vector3f vectorD = quatA.mult(leftSideVertices[3...
Vector3f[] leftSideYes = new Vector3f[4];
leftSideYes[0] = new Vector3f(vectorA);
leftSideYes[1] = new Vector3f(vectorB);
leftSideYes[2] = new Vector3f(vectorC);
leftSideYes[3] = new Vector3f(vectorD);
// Left Wall
Vector2f[] leftSideCoord = new Vector2f[4];
leftSideCoord[0] = new Vector2f(0, 0);
leftSideCoord[1] = new Vector2f(1, 0);
leftSideCoord[2] = new Vector2f(0, 1);
leftSideCoord[3] = new Vector2f(1, 1);
// Indexes. We define the order in which mesh sh...
int[] indexes = {2, 0, 1, 1, 3, 2};
// Setting buffers
leftSide.setBuffer(VertexBuffer.Type.Position, 3...
leftSide.setBuffer(VertexBuffer.Type.TexCoord, 2...
leftSide.setBuffer(VertexBuffer.Type.Index, 1, B...
leftSide.updateBound();
// Create Left of cube
Geometry leftSideGeom = new Geometry("OurMesh", ...
Material leftSideMat = new Material(assetManager...
leftSideMat.setColor("Color", ColorRGBA.White);
leftSideGeom.setMaterial(leftSideMat);
leftSideGeom.setLocalTranslation(0, 0, 3);
leftSideMat.getAdditionalRenderState().setWirefr...
leftSideMat.getAdditionalRenderState().setFaceCu...
rootNode.attachChild(leftSideGeom);
RigidBodyControl leftWallCollision = new RigidBo...
leftSideGeom.addControl(leftWallCollision);
bulletAppState.getPhysicsSpace().add(leftWallCol...
leftWallCollision.setRestitution(0.15f);
leftWallCollision.setFriction(0);
}
private void createBottomSideCube() {
Mesh bottomSide = new Mesh();
Quaternion quatA = new Quaternion();
quatA.fromAngleAxis(-FastMath.HALF_PI, Vector3f....
// Bottom Wall
Vector3f[] bottomSideVertices = new Vector3f[4];
bottomSideVertices[0] = new Vector3f(0, 0, 9);
bottomSideVertices[1] = new Vector3f(0, -9, 9);
bottomSideVertices[2] = new Vector3f(9, 0, 9);
bottomSideVertices[3] = new Vector3f(9, -9, 9);
Vector3f vectorA = quatA.mult(bottomSideVertices...
Vector3f vectorB = quatA.mult(bottomSideVertices...
Vector3f vectorC = quatA.mult(bottomSideVertices...
Vector3f vectorD = quatA.mult(bottomSideVertices...
Vector3f[] bottomSideYes = new Vector3f[4];
bottomSideYes[0] = new Vector3f(vectorA);
bottomSideYes[1] = new Vector3f(vectorB);
bottomSideYes[2] = new Vector3f(vectorC);
bottomSideYes[3] = new Vector3f(vectorD);
// Bottom Wall
Vector2f[] bottomSideCoord = new Vector2f[4];
bottomSideCoord[0] = new Vector2f(0, 0);
bottomSideCoord[1] = new Vector2f(1, 0);
bottomSideCoord[2] = new Vector2f(0, 1);
bottomSideCoord[3] = new Vector2f(1, 1);
// Indexes. We define the order in which mesh sh...
int[] indexes = {2, 0, 1, 1, 3, 2};
// Setting buffers
bottomSide.setBuffer(VertexBuffer.Type.Position,...
bottomSide.setBuffer(VertexBuffer.Type.TexCoord,...
bottomSide.setBuffer(VertexBuffer.Type.Index, 1,...
bottomSide.updateBound();
// Create Bottom of cube
Geometry bottomSideGeom = new Geometry("OurMesh"...
Material bottomSideMat = new Material(assetManag...
bottomSideMat.setColor("Color", ColorRGBA.White);
bottomSideGeom.setMaterial(bottomSideMat);
bottomSideMat.getAdditionalRenderState().setWire...
bottomSideMat.getAdditionalRenderState().setFace...
rootNode.attachChild(bottomSideGeom);
RigidBodyControl bottomWallCollision = new Rigid...
bottomSideGeom.addControl(bottomWallCollision);
bulletAppState.getPhysicsSpace().add(bottomWallC...
bottomWallCollision.setRestitution(0.15f);
bottomWallCollision.setFriction(0);
}
private void createTopSideCube() {
Mesh topSide = new Mesh();
Quaternion quatA = new Quaternion();
quatA.fromAngleAxis(-FastMath.HALF_PI, Vector3f....
// Top Wall
Vector3f[] topSideVertices = new Vector3f[4];
topSideVertices[0] = new Vector3f(0, 0, 0);
topSideVertices[1] = new Vector3f(0, -9, 0);
topSideVertices[2] = new Vector3f(9, 0, 0);
topSideVertices[3] = new Vector3f(9, -9, 0);
Vector3f vectorA = quatA.mult(topSideVertices[0]);
Vector3f vectorB = quatA.mult(topSideVertices[1]);
Vector3f vectorC = quatA.mult(topSideVertices[2]);
Vector3f vectorD = quatA.mult(topSideVertices[3]);
Vector3f[] topSideYes = new Vector3f[4];
topSideYes[0] = new Vector3f(vectorA);
topSideYes[1] = new Vector3f(vectorB);
topSideYes[2] = new Vector3f(vectorC);
topSideYes[3] = new Vector3f(vectorD);
// Top Wall
Vector2f[] topSideCoord = new Vector2f[4];
topSideCoord[0] = new Vector2f(0, 0);
topSideCoord[1] = new Vector2f(1, 0);
topSideCoord[2] = new Vector2f(0, 1);
topSideCoord[3] = new Vector2f(1, 1);
// Indexes. We define the order in which mesh sh...
int[] indexes = {2, 0, 1, 1, 3, 2};
// Setting buffers
topSide.setBuffer(VertexBuffer.Type.Position, 3,...
topSide.setBuffer(VertexBuffer.Type.TexCoord, 2,...
topSide.setBuffer(VertexBuffer.Type.Index, 1, Bu...
topSide.updateBound();
// Create Top of cube
Geometry topSideGeom = new Geometry("OurMesh", t...
Material topSideMat = new Material(assetManager,...
topSideMat.setColor("Color", ColorRGBA.White);
topSideGeom.setMaterial(topSideMat);
topSideMat.getAdditionalRenderState().setWirefra...
topSideMat.getAdditionalRenderState().setFaceCul...
RigidBodyControl topWallCollision = new RigidBod...
topSideGeom.addControl(topWallCollision);
bulletAppState.getPhysicsSpace().add(topWallColl...
topWallCollision.setFriction(0);
topWallCollision.setRestitution(0.15f);
rootNode.attachChild(topSideGeom);
}
}
- Weapon.java
import com.jme3.asset.AssetManager;
import com.jme3.asset.TextureKey;
import com.jme3.bullet.BulletAppState;
import com.jme3.bullet.control.RigidBodyControl;
import com.jme3.material.Material;
import com.jme3.math.ColorRGBA;
import com.jme3.math.Vector3f;
import com.jme3.scene.Geometry;
import com.jme3.scene.Node;
import com.jme3.scene.debug.Arrow;
import com.jme3.scene.shape.*;
import com.jme3.texture.Texture;
/*
* This class creates three types of weapons: a laser be...
* @author yujishimojo
*/
public class Weapon {
private BulletAppState bulletAppState;
private Node rootNode;
private AssetManager assetManager;
public Geometry geoLaserBeam;
public Geometry geoCannonBall;
public Geometry geoArrow;
public Material matLaserBeam;
public Material matCannonBall;
public Material matArrow;
public RigidBodyControl phyLaserBeam;
public RigidBodyControl phyCannonBall;
public RigidBodyControl phyArrow;
int VELOCITY = 100;
public Weapon (AssetManager assetManager, Node rootN...
this.bulletAppState = bulletAppState;
this.rootNode = rootNode;
this.assetManager = assetManager;
}
public void makeLaserBeam (Vector3f location, Vector...
Box createLaserBeam = new Box(Vector3f.ZERO, 0.1...
geoLaserBeam = new Geometry ("Laser Beam", creat...
matLaserBeam = new Material(assetManager, "Commo...
matLaserBeam.setColor("Color", new ColorRGBA(1.0...
geoLaserBeam.setMaterial(matLaserBeam);
rootNode.attachChild(geoLaserBeam);
geoLaserBeam.setLocalTranslation(location);
phyLaserBeam = new RigidBodyControl(1f);
geoLaserBeam.addControl(phyLaserBeam);
bulletAppState.getPhysicsSpace().add(phyLaserBea...
/** Accelerate the physcial ball to shoot it. */
phyLaserBeam.setLinearVelocity(direction.mult(VE...
phyLaserBeam.setGravity(new Vector3f(0, 0, 0));
}
public void removeLaserBeam () {
rootNode.detachChild(geoLaserBeam);
}
public void makeCannonBall (Vector3f location, Vecto...
/** Create a ball geometry. */
Sphere createCannonBall = new Sphere(32, 32, 0.3...
geoCannonBall = new Geometry("Cannon Ball", crea...
createCannonBall.setTextureMode(Sphere.TextureMo...
matCannonBall = new Material(assetManager, "Comm...
TextureKey key = new TextureKey("Textures/Terrai...
key.setGenerateMips(true);
Texture tex = assetManager.loadTexture(key);
matCannonBall.setTexture("ColorMap", tex);
geoCannonBall.setMaterial(matCannonBall);
rootNode.attachChild(geoCannonBall);
/** Position the ball */
geoCannonBall.setLocalTranslation(location);
/** Make the ball physcial with a mass > 0.0f */
phyCannonBall = new RigidBodyControl(1f);
/** Add physical ball to physics space. */
geoCannonBall.addControl(phyCannonBall);
bulletAppState.getPhysicsSpace().add(phyCannonBa...
/** Accelerate the physcial ball to shoot it. */
phyCannonBall.setLinearVelocity(direction.mult(V...
phyCannonBall.setGravity(new Vector3f(0, 0, 0));
}
public void removeCannonBall () {
rootNode.detachChild(geoCannonBall);
}
public void makeArrow (Vector3f location, Vector3f d...
Arrow createArrow = new Arrow(direction.mult(1));
createArrow.setLineWidth(2);
geoArrow = new Geometry("arrow", createArrow);
matArrow = new Material(assetManager, "Common/Ma...
matArrow.setColor("Color", new ColorRGBA(0.9f,0....
geoArrow.setMaterial(matArrow);
rootNode.attachChild(geoArrow);
geoArrow.setLocalTranslation(location);
phyArrow = new RigidBodyControl(1f);
geoArrow.addControl(phyArrow);
bulletAppState.getPhysicsSpace().add(phyArrow);
phyArrow.setLinearVelocity(direction.mult(VELOCI...
phyArrow.setGravity(new Vector3f(0, 0, 0));
}
public void removeArrow () {
rootNode.detachChild(geoArrow);
}
}
- ShootingObjectsMain.java
import com.jme3.app.SimpleApplication;
import com.jme3.audio.AudioNode;
import com.jme3.bullet.BulletAppState;
import com.jme3.collision.CollisionResults;
import com.jme3.font.BitmapText;
import com.jme3.input.KeyInput;
import com.jme3.input.MouseInput;
import com.jme3.input.controls.ActionListener;
import com.jme3.input.controls.KeyTrigger;
import com.jme3.input.controls.MouseButtonTrigger;
import com.jme3.math.Ray;
import com.jme3.math.Vector3f;
import com.jme3.scene.Node;
import java.util.Random;
import java.util.Timer;
import javax.swing.JOptionPane;
/*
* This is the main class of the project.
* The functions are: text display on the screen, file e...
* and event handlers for key presses and collision dete...
* @author yujishimojo
*/
public class ShootingObjectsMain extends SimpleApplicati...
private java.io.PrintWriter output;
private BulletAppState bulletAppState;
private Cube createCube;
private Target target;
private Weapon weapon;
private int count = 0;
Node shootables;
Timer timeClone;
private int gameTimeCount = 0;
private float shotsFired = 0;
private float shotsHit = 0;
private int destroyedTarget = 0;
private float shotAccuracy = 100;
private int points = 0;
int weaponState = 0;
BitmapText timePlayed;
BitmapText bulletsFired;
BitmapText bulletsHit;
BitmapText accuracy;
BitmapText targetsDestroyed;
BitmapText pointSum;
BitmapText selectedWeapon;
private int ball1 = 0;
private int ball2 = 0;
private int ball3 = 0;
private int ball4 = 0;
private AudioNode laserBeamAudio;
private AudioNode cannonBallAudio;
private AudioNode arrowAudio;
private AudioNode objectExplodeAudio;
public static void main(String[] args) {
ShootingObjectsMain shootingObjectsMain = new Sh...
// Starts the game
shootingObjectsMain.start();
}
@Override
public void simpleInitApp() {
// Declares string fileName to be used in if sta...
String fileName;
// Declares java.io.File file
java.io.File file;
// Configure cam to look at scene
cam.setLocation(new Vector3f(4.3f, 4.8f, 25f));
cam.lookAt(new Vector3f(4.5f, 4.5f, 0), Vector3f...
flyCam.setMoveSpeed(0);
bulletAppState = new BulletAppState();
stateManager.attach(bulletAppState);
bulletAppState.getPhysicsSpace().setAccuracy(0.0...
bulletAppState.getPhysicsSpace().setGravity(new ...
// Set up GUI
initCrosshair();
// Set up shooter
initKeys();
// Set up audio
initAudio();
// Create shootables node
shootables = new Node("shootables");
// Creates the first cube
createCube = new Cube(assetManager, rootNode, bu...
// Creates the first cube
target = new Target(assetManager, rootNode, shoo...
// Instantiate the Weapon class
weapon = new Weapon(assetManager, rootNode, bull...
// User determines file name
fileName = JOptionPane.showInputDialog(null, "Wh...
// Creates new file using new name
file = new java.io.File(fileName + "_ShootingObj...
// Instatiates geometries for weapons to avoid N...
weapon.makeLaserBeam(cam.getLocation(), cam.getD...
weapon.makeCannonBall(cam.getLocation(), cam.get...
weapon.makeArrow(cam.getLocation(), cam.getDirec...
try {
// Create a Scanner for the file
output = new java.io.PrintWriter(file);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void stop() {
output.println("Bullets Fired: " + shotsFired);
output.println("Bullets Hit: " + shotsHit);
output.println("Accuracy: " + shotAccuracy + "%");
output.println("Targets Destroyed: " + destroyed...
output.println("Points: " + points);
output.flush();
output.close();
System.exit(0);
}
@Override
public void simpleUpdate(float tpf) {
// Update selected weapon
updateWeaponDisplay();
// Update vector position to text file
if (getTimer().getTimeInSeconds() >= 1) {
getTimer().reset();
count++;
gameTimeCount++;
updateTime();
// Clear weapons to display one by one
weapon.removeLaserBeam();
weapon.removeCannonBall();
weapon.removeArrow();
// Gravity changes every 6 seconds.
if (count > 5) {
Random random = new Random();
Vector3f setGravity = new Vector3f((rand...
bulletAppState.getPhysicsSpace().setGrav...
System.out.println("Gravity Location" + ...
System.out.println("5 seconds");
bulletAppState.getPhysicsSpace().applyGr...
count = 0;
}
// Stops game automatically
if (gameTimeCount >= 120) {
JOptionPane.showMessageDialog(null, "Two...
// Shows the final results
JOptionPane.showMessageDialog(null,
"Bullets Fired: " + shotsFired +...
+ "Bullets Hit: " + shotsHit + "...
+ "Accuracy: " + shotAccuracy + ...
+ "Targets Destroyed: " + destro...
+ "Points: " + points,
"Results:", JOptionPane.INFORMAT...
stop();
}
}
}
// Creates key to shoot
private void initKeys() {
inputManager.addMapping("Shoot",
new KeyTrigger(KeyInput.KEY_SPACE), // t...
new MouseButtonTrigger(MouseInput.BUTTON...
inputManager.addListener(actionListener, "Shoot");
inputManager.addMapping("Laser", new KeyTrigger(...
inputManager.addListener(actionListener, new Str...
inputManager.addMapping("Cannon", new KeyTrigger...
inputManager.addListener(actionListener, new Str...
inputManager.addMapping("Arrow", new KeyTrigger(...
inputManager.addListener(actionListener, new Str...
}
// Create shooting action listener
private ActionListener actionListener = new ActionLi...
private int ws; // A local variable to manage we...
public void onAction(String name, boolean keyPre...
if (name.equals("Shoot") && !keyPressed) {
// Clear the weapon
if (ws == 0) {
weapon.removeLaserBeam();
} else if (ws == 1) {
weapon.removeCannonBall();
} else if (ws == 2) {
weapon.removeArrow();
}
// Makes the weapon
if (ws == 0) {
weapon.makeLaserBeam(cam.getLocation...
} else if (ws == 1) {
weapon.makeCannonBall(cam.getLocatio...
} else if (ws == 2) {
weapon.makeArrow(cam.getLocation(), ...
}
// This is for removing the weapon for c...
long startTime = System.currentTimeMilli...
// Plays shooting sound
if (ws == 0) {
laserBeamAudio.playInstance();
} else if (ws == 1) {
cannonBallAudio.playInstance();
} else if (ws == 2) {
arrowAudio.playInstance();
}
// Reset results list.
CollisionResults results = new Collision...
// Aim the ray from cam loc to cam direc...
Ray ray = new Ray(cam.getLocation(), cam...
// Collect intersections between Ray and...
shootables.collideWith(ray, results);
// If results is 0 then console prints y...
if (results.size() > 0) {
for (int i = 0; i < results.size(); ...
// Outputs results for all colli...
float dist = results.getCollisio...
Vector3f pt = results.getCollisi...
String hit = results.getCollisio...
// Removes the weapon within 0.01s
if (System.currentTimeMillis() -...
if (ws == 0) {
weapon.removeLaserBeam();
} else if (ws == 1) {
weapon.removeCannonBall(...
} else if (ws == 2) {
weapon.removeArrow();
}
startTime = 0;
}
createNewCubes(hit); ...
System.out.println("* Collision ...
System.out.println(" You shot "...
shotsHit++;
break;
}
} else {
System.out.println("You missed!");
}
// Update shots fired on GUI
shotsFired++;
updateShotsFired();
}
// Changes the value of the weapon state
if (name.equals("Laser") && !keyPressed) {
ws = 0;
weaponState = 0;
} else if (name.equals("Cannon") && !keyPres...
ws = 1;
weaponState = 1;
} else if (name.equals("Arrow") && !keyPress...
ws = 2;
weaponState = 2;
}
}
};
// Create audio to attach to scene
private void initAudio() {
laserBeamAudio = new AudioNode(assetManager, "So...
laserBeamAudio.setLooping(false);
laserBeamAudio.setVolume(2);
rootNode.attachChild(laserBeamAudio);
cannonBallAudio = new AudioNode(assetManager, "S...
cannonBallAudio.setLooping(false);
cannonBallAudio.setVolume(1);
rootNode.attachChild(cannonBallAudio);
arrowAudio = new AudioNode(assetManager, "Sounds...
arrowAudio.setLooping(false);
arrowAudio.setVolume(2);
rootNode.attachChild(arrowAudio);
objectExplodeAudio = new AudioNode(assetManager,...
objectExplodeAudio.setLooping(false);
objectExplodeAudio.setVolume(4);
rootNode.attachChild(objectExplodeAudio);
}
// Create shooting action attached to left mouse click
private void initCrosshair() {
guiNode.detachAllChildren();
guiFont = assetManager.loadFont("Interface/Fonts...
// Creates Crosshair
BitmapText ch = new BitmapText(guiFont, false);
ch.setSize(guiFont.getCharSet().getRenderedSize(...
ch.setText("+"); // crosshairs
ch.setLocalTranslation( // center
settings.getWidth() / 2 - guiFont.getCha...
settings.getHeight() / 2 + ch.getLineHei...
guiNode.attachChild(ch);
// Creates Time Played Text
timePlayed = new BitmapText(guiFont, false);
timePlayed.setSize(guiFont.getCharSet().getRende...
timePlayed.setText("Time: " + gameTimeCount + " ...
timePlayed.setLocalTranslation(0, 475, 0);
guiNode.attachChild(timePlayed);
// Creates Number of Bullets Fired Text
bulletsFired = new BitmapText(guiFont, false);
bulletsFired.setSize(guiFont.getCharSet().getRen...
bulletsFired.setText("Bullets Fired: " + shotsFi...
bulletsFired.setLocalTranslation(0, 450, 0);
guiNode.attachChild(bulletsFired);
// Creates Number of Bullets Hit Text
bulletsHit = new BitmapText(guiFont, false);
bulletsHit.setSize(guiFont.getCharSet().getRende...
bulletsHit.setText("Bullets Hit: " + shotsHit);
bulletsHit.setLocalTranslation(0, 425, 0);
guiNode.attachChild(bulletsHit);
// Creates Accuracy Text
accuracy = new BitmapText(guiFont, false);
accuracy.setSize(guiFont.getCharSet().getRendere...
accuracy.setText("Accuracy: " + shotAccuracy + "...
accuracy.setLocalTranslation(0, 400, 0);
guiNode.attachChild(accuracy);
// Creates Number of Targets Destroyed Text
targetsDestroyed = new BitmapText(guiFont, false);
targetsDestroyed.setSize(guiFont.getCharSet().ge...
targetsDestroyed.setText("Targets Destroyed: " +...
targetsDestroyed.setLocalTranslation(0, 375, 0);
guiNode.attachChild(targetsDestroyed);
// Creates Number of Targets Destroyed Text
pointSum = new BitmapText(guiFont, false);
pointSum.setSize(guiFont.getCharSet().getRendere...
pointSum.setText("Points: " + points);
pointSum.setLocalTranslation(0, 350, 0);
guiNode.attachChild(pointSum);
// Creates
selectedWeapon = new BitmapText(guiFont, false);
selectedWeapon.setSize(guiFont.getCharSet().getR...
selectedWeapon.setText("Laser Beam"); // default...
selectedWeapon.setLocalTranslation(540, 475, 0);
guiNode.attachChild(selectedWeapon);
}
private void updateTime() {
timePlayed.setText("Time: " + gameTimeCount + " ...
}
private void updateShotsFired() {
shotAccuracy = (shotsHit / shotsFired) * 100;
bulletsFired.setText("Bullets Fired: " + shotsFi...
bulletsHit.setText("Bullets Hit: " + shotsHit);
accuracy.setText("Accuracy: " + shotAccuracy + "...
targetsDestroyed.setText("Targets Destroyed: " +...
pointSum.setText("Points: " + points);
}
// Set the text on the gui display
public void updateWeaponDisplay() {
if (weaponState == 0) {
selectedWeapon.setText("Laser Beam");
} else if (weaponState == 1) {
selectedWeapon.setText("Cannon Ball");
} else {
selectedWeapon.setText("Arrow");
}
}
private void createNewCubes(String hit) {
if (hit.equals("Ball 1")) {
ball1++;
if (ball1 == 1) {
shootables.detachChildNamed(hit);
objectExplodeAudio.playInstance();
target.createBall1();
points = points + 2;
destroyedTarget++;
ball1 = 0;
}
} else if (hit.equals("Ball 2")) {
ball2++;
if (ball2 == 2) {
shootables.detachChildNamed(hit);
objectExplodeAudio.playInstance();
target.createBall2();
points = points + 6;
destroyedTarget++;
ball2 = 0;
}
} else if (hit.equals("Ball 3")) {
ball3++;
if (ball3 == 3) {
shootables.detachChildNamed(hit);
objectExplodeAudio.playInstance();
target.createBall3();
points = points + 10;
destroyedTarget++;
ball3 = 0;
}
} else if (hit.equals("Ball 4")) {
ball4++;
if (ball4 == 4) {
shootables.detachChildNamed(hit);
objectExplodeAudio.playInstance();
target.createBall4();
points = points + 16;
destroyedTarget++;
ball4 = 0;
}
}
}
}
- [[YouTube Video:https://www.youtube.com/watch?v=agwQ4_n...
- Document
#ref(CMSC325_FinalProject.pdf)
ページ名: