Why does the spaceship not appear? - java

I use jmonkeyengine and I downloaded a spaceship model from blendswap and converted it to j3o to load it with jmonkeyengine for a space scene where I can control the ship and travel around. However the spaceship is not loaded. The space and planets appear but I want the spaceship to be what the player controls and not first-person like it appears.
I expect the spaceship to appear because I load it without errors and add it to the scene but it stil doesn't show.
//add saucer
ufoNode = (Node) assetManager
.loadModel("usaucer_v01.j3o");
rootNode.attachChild(ufoNode);
What should I do to make the spaceship appear? The program is
public class PlanetSimpleTest extends SimpleApplication {
private PlanetAppState planetAppState;
private Geometry mark;
private Node ufoNode;
private GameCharControl ufoControl;
Camera cam2;
public static void main(String[] args){
AppSettings settings = new AppSettings(true);
settings.setResolution(1024,768);
PlanetSimpleTest app = new PlanetSimpleTest();
app.setSettings(settings);
//app.showSettings = true;
app.start();
}
#Override
public void simpleInitApp() {
// Only show severe errors in log
java.util.logging.Logger.getLogger("com.jme3").setLevel(java.util.logging.Level.SEVERE);
// Toggle mouse cursor
inputManager.addMapping("TOGGLE_CURSOR",
new MouseButtonTrigger(MouseInput.BUTTON_LEFT),
new KeyTrigger(KeyInput.KEY_SPACE));
inputManager.addListener(actionListener, "TOGGLE_CURSOR");
// Toggle wireframe
inputManager.addMapping("TOGGLE_WIREFRAME",
new KeyTrigger(KeyInput.KEY_T));
inputManager.addListener(actionListener, "TOGGLE_WIREFRAME");
// Collision test
inputManager.addMapping("COLLISION_TEST",
new MouseButtonTrigger(MouseInput.BUTTON_RIGHT));
inputManager.addListener(actionListener, "COLLISION_TEST");
// Setup camera
// In orbit
this.getCamera().setLocation(new Vector3f(0f, 0f, 180000f));
// On surface
//this.getCamera().setLocation(new Vector3f(-6657.5254f, 27401.822f, 57199.777f));
//this.getCamera().lookAtDirection(new Vector3f(0.06276598f, 0.94458306f, -0.3222158f), Vector3f.UNIT_Y);
// Add sun
//PointLight sun = new PointLight();
//sun.setPosition(new Vector3f(-100000f,0,180000f));
DirectionalLight sun = new DirectionalLight();
sun.setDirection(new Vector3f(-.1f, 0f, -1f));
sun.setColor(new ColorRGBA(0.75f,0.75f,0.75f,1.0f));
rootNode.addLight(sun);
// Add sky
Node sceneNode = new Node("Scene");
sceneNode.attachChild(Utility.createSkyBox(this.getAssetManager(), "Textures/blue-glow-1024.dds"));
rootNode.attachChild(sceneNode);
// Create collision test mark
Sphere sphere = new Sphere(30, 30, 5f);
mark = new Geometry("mark", sphere);
Material mark_mat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
mark_mat.setColor("Color", ColorRGBA.Red);
mark.setMaterial(mark_mat);
// Add planet app state
planetAppState = new PlanetAppState(rootNode, sun);
stateManager.attach(planetAppState);
// Add planet
FractalDataSource planetDataSource = new FractalDataSource(4);
planetDataSource.setHeightScale(900f);
Planet planet = Utility.createEarthLikePlanet(getAssetManager(), 63710.0f, null, planetDataSource);
planetAppState.addPlanet(planet);
rootNode.attachChild(planet);
// Add moon
FractalDataSource moonDataSource = new FractalDataSource(5);
moonDataSource.setHeightScale(300f);
Planet moon = Utility.createMoonLikePlanet(getAssetManager(), 20000, moonDataSource);
planetAppState.addPlanet(moon);
rootNode.attachChild(moon);
moon.setLocalTranslation(-150000f, 0f, 0f);
//add saucer
ufoNode = (Node) assetManager
.loadModel("usaucer_v01.j3o");
ufoNode.setLocalScale(100f);
rootNode.attachChild(ufoNode);
}
#Override
public void simpleUpdate(float tpf) {
// slow camera down as we approach a planet
Planet planet = planetAppState.getNearestPlanet();
if (planet != null && planet.getPlanetToCamera() != null) {
this.getFlyByCamera().setMoveSpeed(
FastMath.clamp(planet.getDistanceToCamera(), 100, 100000));
}
}
private ActionListener actionListener = new ActionListener(){
public void onAction(String name, boolean pressed, float tpf){
if (name.equals("TOGGLE_CURSOR") && !pressed) {
if (inputManager.isCursorVisible()) {
inputManager.setCursorVisible(false);
} else {
inputManager.setCursorVisible(true);
}
}
if (name.equals("TOGGLE_WIREFRAME") && !pressed) {
for (Planet planet: planetAppState.getPlanets()) {
planet.toogleWireframe();
}
}
if (name.equals("COLLISION_TEST") && !pressed) {
CollisionResults results = new CollisionResults();
Ray ray = new Ray(cam.getLocation(), cam.getDirection());
// Test collision with closest planet's terrain only
planetAppState.getNearestPlanet().getTerrainNode().collideWith(ray, results);
System.out.println("----- Collisions? " + results.size() + "-----");
for (int i = 0; i < results.size(); i++) {
// For each hit, we know distance, impact point, name of geometry.
float dist = results.getCollision(i).getDistance();
Vector3f pt = results.getCollision(i).getContactPoint();
String hit = results.getCollision(i).getGeometry().getName();
System.out.println("* Collision #" + i);
System.out.println(" You shot " + hit + " at " + pt + ", " + dist + " wu away.");
}
if (results.size() > 0) {
// The closest collision point is what was truly hit:
CollisionResult closest = results.getClosestCollision();
// Let's interact - we mark the hit with a red dot.
mark.setLocalTranslation(closest.getContactPoint());
rootNode.attachChild(mark);
} else {
// No hits? Then remove the red mark.
rootNode.detachChild(mark);
}
}
}
};
}
The spaceship I took from here and converted to jme3:s binary format j3o and added to the game, but I'm obviously not doing everything to make it appear in the scene. I've gotten this far in the jmonkeyengine IDE but then when I load it in Eclipse it doesn't work so I'm trying to create the scene with the jmonkeyengine IDE first.
I then try and create a scene with the spaceship but I get an Exception in the JME SDK.
After adding the lines
ufoNode.setLocalScale(300f);
ufoNode.setLocalTranslation((new Vector3f(10f, 10f, 180010f)));
the spaceship does appear but maybe not perfect. Can it be improved?
Update 140104 17:54 CET
It seems the spaceship was upside down(?) so I've rotated it now.
//add saucer
ufoNode = (Node) assetManager.loadModel("usaucer_v01.j3o");
ufoNode.setLocalScale(1000f);
ufoNode.setLocalTranslation((new Vector3f(10f, 10f, 165000f)));
/* This quaternion stores a 180 degree rolling rotation */
Quaternion roll180 = new Quaternion();
roll180.fromAngleAxis(FastMath.PI , new Vector3f(0,0,1));
/* The rotation is applied: The object rolls by 180 degrees. */
ufoNode.setLocalRotation(roll180);
rootNode.attachChild(ufoNode);

You add the spaceship at 0,0,0 (as you don't move it) but have moved your camera to 0f, 0f, 180000f. Most likely it is out of shot or far too small to see.
Try loading the spaceship within the jME SDK and confirm that it works within the engine using the scene editor there.
If that works then try a simple test scene just dropping the spaceship and camera in - then once that works move a step at a time towards your desired setting.

Related

Moving drawn shape to the location where the mouse is clicked using select button in processing

The current project allows me to draw and select the drawn shape, what I would like to do is once I press the button select and click on the shape, I would like to move the shape to the location where the mouse is clicked. As seen in the example which I have provided below.
I have inserted one part of the code as the code is big to upload here, I have uploaded the full code to https://github.com/Muhammad-786/DrawingShapes
Example of moving shapes: https://github.com/Muhammad-786/MovingShapes
SimpleUI myUI;
DrawingList drawingList;
String toolMode = "";
void setup() {
size(900,600);
myUI = new SimpleUI();
drawingList = new DrawingList();
RadioButton rectButton = myUI.addRadioButton("rect", 5, 50, "group1");
myUI.addRadioButton("ellipse", 5, 80, "group1");
myUI.addRadioButton("line", 5, 110, "group1");
myUI.addRadioButton("image", 5, 140, "group1");
rectButton.selected = true;
toolMode = rectButton.UILabel;
// add a new tool .. the select tool
myUI.addRadioButton("select", 5, 200, "group1");
myUI.addCanvas(110,10,780,580);
}
void draw() {
background(255);
drawingList.drawMe();
myUI.update();
}
void handleUIEvent(UIEventData eventData){
// if from a tool-mode button, the just set the current tool mode string
if(eventData.uiComponentType == "RadioButton"){
toolMode = eventData.uiLabel;
return;
}
// only canvas events below here! First get the mouse point
if(eventData.eventIsFromWidget("canvas")==false) return;
PVector p = new PVector(eventData.mousex, eventData.mousey);
// this next line catches all the tool shape-drawing modes
// so that drawing events are sent to the display list class only if the current tool
// is a shape drawing tool
if( toolMode.equals("rect") ||
toolMode.equals("ellipse") ||
toolMode.equals("line") ||
toolMode.equals("image")){
drawingList.handleMouseDrawEvent(toolMode,eventData.mouseEventType, p);
return;
}
// if the current tool is "select" then do this
if( toolMode.equals("select") ) {
drawingList.trySelect(eventData.mouseEventType, p);
}
}
void keyPressed(){
if(key == BACKSPACE){
drawingList.deleteSelected();
}
}

Which Keys are used to move while using KeyNavigatorBehavior? How do I set them?

I've learned something about Java3D and I wondered how to move around the Camera using keystrokes. I've found the KeyNavigatorBehavior and set it up, just there is no Key doing anything. How do I use this Behavior properly?
Here I got my method setting the Behavior:
protected BranchGroup buildViewBranch(Canvas3D c) {
BranchGroup viewBranch = new BranchGroup();
Transform3D viewXfm = new Transform3D();
viewXfm.set(new Vector3f(0.0f, 0.0f, 10.0f));
TransformGroup viewXfmGroup = new TransformGroup(viewXfm);
viewXfmGroup.setCapability(TransformGroup.ALLOW_TRANSFORM_READ);
viewXfmGroup.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE);
BoundingSphere movingBounds = new BoundingSphere(new Point3d(0.0, 0.0,0.0), 100.0);
BoundingLeaf boundLeaf = new BoundingLeaf(movingBounds);
ViewPlatform myViewPlatform = new ViewPlatform();
viewXfmGroup.addChild(boundLeaf);
PhysicalBody myBody = new PhysicalBody();
PhysicalEnvironment myEnvironment = new PhysicalEnvironment();
viewXfmGroup.addChild(myViewPlatform);
viewBranch.addChild(viewXfmGroup);
View myView = new View();
myView.addCanvas3D(c);
myView.attachViewPlatform(myViewPlatform);
myView.setPhysicalBody(myBody);
myView.setPhysicalEnvironment(myEnvironment);
KeyNavigatorBehavior keyNav = new KeyNavigatorBehavior(viewXfmGroup);
keyNav.setSchedulingBounds(movingBounds);
viewBranch.addChild(keyNav);
return viewBranch;
}
Here are the lines setting the VirtualUniverse:
group = new BranchGroup();
VirtualUniverse universe = new VirtualUniverse();
Locale locale = new Locale(universe);
locale.addBranchGraph(this.buildViewBranch(canvas));
locale.addBranchGraph(group);
I found the answer myself:
You have to activate KeyboardMouse (Alt + Shift + Num) and deactivate numlock:
Keys are: arrows + page up/down (also on the numlock)

How to hide or remove javafx tooltip when it is triggered manually?

I have been trying to figure out a way to hide this tooltip when it is triggered by a function and shown in the scene. This is my function.
private void ValidateRequired(TextField field){
Tooltip errorTip = null;
if(field.getText().equals("")){
field.getStyleClass().add("errorField");
errorTip = new Tooltip("This is required");
errorTip.getStyleClass().removeAll();
Scene scene = field.getScene();
scene.getStylesheets().add(this.getClass().getResource("../css/sale.css").toExternalForm());
errorTip.getStyleClass().add("errorTip");
Point2D p = field.localToScene(0.0, 0.0);
errorTip.show(field,p.getX()
+ field.getScene().getX() + field.getScene().getWindow().getX(), p.getY()
+ field.getScene().getY() + field.getScene().getWindow().getY()+field.getHeight()+2);
}
else{
errorTip.hide();
}
}
This function is called when Textfield lose focus. This function get called by the following listener.
currentField.focusedProperty().addListener((ov, oldV, newV) -> {
if (!newV) {
ValidateRequired(currentField);
}
else{
}
});
You are creating a new Tooltip every time the ValidateRequired method (BTW please use proper naming conventions) is called. So when the method is called with non-empty text, you are not hiding the same tooltip you previously showed (and so the previously-showed one remains shown).
Instead, create one tooltip and show/hide it:
private final Tooltip errorTip = new Tooltip();
// ...
private void ValidateRequired(TextField field){
if(field.getText().equals("")){
field.getStyleClass().add("errorField");
errorTip.setText("This is required");
errorTip.getStyleClass().removeAll();
Scene scene = field.getScene();
scene.getStylesheets().add(this.getClass().getResource("../css/sale.css").toExternalForm());
errorTip.getStyleClass().add("errorTip");
Point2D p = field.localToScene(0.0, 0.0);
errorTip.show(field,p.getX()
+ field.getScene().getX() + field.getScene().getWindow().getX(), p.getY()
+ field.getScene().getY() + field.getScene().getWindow().getY()+field.getHeight()+2);
}
else{
errorTip.setText("");
errorTip.hide();
}
}

Insert vertex inside a Graph

I want to add a new vertex inside an existing graph.
So I created a new cell and i'm attempted to reconnected my edge but my graph doesn't update (for the edges)
This is my code :
mxGraph graph = editor.getGraph();
mxCell selectedElt = (mxCell) graph.getSelectionCell();
Object cells[] = { selectedElt };
if (selectedElt.isEdge()) {
// cell is an edge, so we have source and target
System.out.println("Source : " + selectedElt.getSource().getId());
System.out.println("Target : " + selectedElt.getTarget().getId());
} else {
// edge before
mxCell beforeEdge = (mxCell) selectedElt.getEdgeAt(0);
// edge after
mxCell afterEdge = (mxCell) selectedElt.getEdgeAt(1);
// moving down the selected cell
graph.moveCells(cells, 0, 50);
// create a new vertex
GraphStyle graphStyle = new GraphStyle(graph);
mxCell cell = new mxCell("AAM",
new mxGeometry(selectedElt.getGeometry().getX(), selectedElt.getGeometry().getY(), 80, 50),
graphStyle.getCalculatorStyleName());
cell.setVertex(true);
beforeEdge.setTarget(cell);
graph.insertEdge(graph.getDefaultParent(), "e33", "", cell, selectedElt);
graph.addCell(cell);
graph.repaint();
}
Instead of calling beforeEdge.setTarget(cell) try cell.insertEdge(beforeEdge, false). This will remove the Edge from the previous vertex and add it to the new vertex.
Btw. I suggest to wrapp your code into a try-finally block, like this:
graph.getModel().beginUpdate();
try {
// do all the graph related stuff
}
finally {
graph.getModel().endUpdate();
}

OSM get current map perspective

I'm wondering how to get my current camera perspective in an OSM map. I want to save my current camera perspective so that when I refresh the map (with mapView.invalidate()), it will go back to where I was before the refresh (zoom level and latitude/longitude). Right now, I'm only going back to a default location, which is not what I want. I've been searching for a while to no avail, any help is appreciated.
I currently have an update() method which, when called, attempts to reset the zoom level:
void update(boolean zoomToFit) {
if(selectedStop != null) {
new GetBusInfo().execute(selectedStop);
selectedBus = null;
}
busLocnOverlay.removeAllItems();
mapView.invalidate();
Log.d(LOG_TAG, "update - ZOOM_TO_SPAN1: " + ZOOM_TO_SPAN_1);
if (ZOOM_TO_SPAN_1 != 0 && ZOOM_TO_SPAN_2 != 0)
mapView.getController().zoomToSpan(ZOOM_TO_SPAN_1, ZOOM_TO_SPAN_2);
}
It's currently not working, which leads me to think that there's something else responsible for setting the zoom level. ZOOM_TO_SPAN1/2 are set when I plot objects onto the map - the code snippet is quite long so I won't put all of it, but it basically looks like this:
private void plotBuses(boolean zoomToFit) {
// bunch of stuff here
for (GeoPoint p : points) {
int lat = p.getLatitudeE6();
int lon = p.getLongitudeE6();
maxLat = Math.max(lat, maxLat);
minLat = Math.min(lat, minLat);
maxLon = Math.max(lon, maxLon);
minLon = Math.min(lon, minLon);
}
mapController.zoomToSpan(Math.abs(maxLat - minLat), Math.abs(maxLon - minLon));
mapController.animateTo(new GeoPoint( (maxLat + minLat)/2, (maxLon + minLon)/2 ));
ZOOM_TO_SPAN_1 = Math.abs(maxLat - minLat);
ZOOM_TO_SPAN_2 = Math.abs(maxLon - minLon);
}
}

Categories

Resources