Java3D selbstgeschriebener Keybehavior mit voids

Developer_Y

Gesperrt
Hi Javaianer,
ich habe ein komplexes Spiele System aufgebaut, das aus 6 Klassen besteht,
nun aber habe ich auch einen KEybehavior geschrieben, Es soll ein 3DVideospiel werden,
nun in jeden videospiel ist es doch so, dass wenn man die eine Taste drückt die Figur sich bewegt, und wenn nicht dann ist keine Bewegung vorhanden.

Gehen wir hier nicht zu tief rein, also
ich habe nun in der Klasse Keybehavior einen void eingesetzt, PlatformGeometryPreparation, ich weiß nicht wie ich ihn nun einbaue, kann mir einer von euch helfen?
Code:
import java.awt.AWTEvent;
import java.awt.event.*;
import java.util.Enumeration;
import javax.media.j3d.*;
import javax.vecmath.*;
import com.sun.j3d.utils.behaviors.vp.*;
import com.sun.j3d.utils.geometry.Sphere;
import com.sun.j3d.utils.universe.PlatformGeometry;


public class KeyBehavior extends ViewPlatformBehavior
{
  // move and rotation constants for comms. with BirdsEye object
  private static final int FORWARD = 0;
  private static final int LEFT = 1;
  private static final int BACK = 2;
  private static final int RIGHT = 3;

  private final static double MOVE_AMT = 0.2;
  private final static double ROT_AMT = Math.PI / 40.0;  // 90 degrees

  private static final Vector3d VFWD = new Vector3d(0,0,-MOVE_AMT);
  private static final Vector3d VBACK = new Vector3d(0,0,MOVE_AMT);
  private static final Vector3d VLEFT = new Vector3d(-MOVE_AMT,0,0);
  private static final Vector3d VRIGHT = new Vector3d(MOVE_AMT,0,0);
  private static final Vector3d VDOWN = new Vector3d(0, -MOVE_AMT ,0);
  private static final Vector3d VUP = new Vector3d(0, MOVE_AMT ,0);

  // key names
  private int forwardKey = KeyEvent.VK_UP;
  private int backKey = KeyEvent.VK_DOWN;
  private int leftKey = KeyEvent.VK_LEFT;
  private int rightKey = KeyEvent.VK_RIGHT;

  private WakeupCondition keyPress;

  private MazeManager mm;    // for checking moves
  private PlatformGeometry gm;    // for PlattformG
  private BirdsEye be;       // player moves/turns are sent to be
  private int zOffset;       // to stop movement down below the floor
  private TransformGroup camera2TG;   // for affecting the back-facing camera

  // for repeated calcs
  private Transform3D t3d = new Transform3D();
  private Transform3D toMove = new Transform3D();
  private Transform3D toRot = new Transform3D();
  private Vector3d trans = new Vector3d();

  private Appearance app;


  public KeyBehavior(MazeManager mazeMan, BirdsEye bird, TransformGroup c2,PlatformGeometry pg)
  {
    keyPress = new WakeupOnAWTEvent( KeyEvent.KEY_PRESSED );
    mm = mazeMan;
    gm = pg;
    be = bird;
    camera2TG = c2;
    zOffset = 0;
  }

  public void initialize()
  { wakeupOn( keyPress ); }


  public void processStimulus( Enumeration criteria )
  {
    WakeupCriterion wakeup;
    AWTEvent[] event;

    while( criteria.hasMoreElements() ) {
      wakeup = (WakeupCriterion) criteria.nextElement();
      if( wakeup instanceof WakeupOnAWTEvent ) {
        event = ((WakeupOnAWTEvent)wakeup).getAWTEvent();
        for( int i = 0; i < event.length; i++ ) {
          if( event[i].getID() == KeyEvent.KEY_PRESSED )
            processKeyEvent((KeyEvent)event[i]);
        }
      }
    }
    wakeupOn( keyPress );
  } // end of processStimulus()



  private void processKeyEvent(KeyEvent eventKey)
  {
    int keyCode = eventKey.getKeyCode();
    if( eventKey.isAltDown() )  
      altMove(keyCode);
    else
      standardMove(keyCode);
  
    	
  } 
  private void PlatformGeometryPreparation(int keycode)
  {
	  if(keycode == forwardKey)	  {
	  app.setPolygonAttributes(new PolygonAttributes(PolygonAttributes.POLYGON_POINT,PolygonAttributes.CULL_NONE,0));
	  gm.addChild(new Sphere(1f,Sphere.GENERATE_NORMALS_INWARD,80,app));
	  }
   }

  private void standardMove(int keycode)
  {

	  
    if(keycode == forwardKey)
      moveBy(VFWD, FORWARD, VBACK);   // args: main camera, bird's eye, back camera
    else if(keycode == backKey)
      moveBy(VBACK, BACK, VFWD);
    else if(keycode == leftKey)
      doRotateY(ROT_AMT, LEFT);
    else if(keycode == rightKey)
      doRotateY(-ROT_AMT, RIGHT);
  }

  private void altMove(int keycode)
  {
    if(keycode == backKey) {  // move down
      if (zOffset > 0) {
        doMove(VDOWN);  // no testing using moveBy()
        doMoveC2(VDOWN);
        zOffset--;
      }
    }
    else if(keycode == forwardKey) {  // move up
      doMove(VUP);   // no testing using moveBy()
      doMoveC2(VUP);
      zOffset++;
    }
    else if(keycode == leftKey)
      moveBy(VLEFT, LEFT, VRIGHT);   // left for main camera, right for back camera
    else if(keycode == rightKey)
      moveBy(VRIGHT, RIGHT, VLEFT);
  } // end of altMove()


  
  // ------------------ moves -----------------------------

  private void moveBy(Vector3d theMove, int dir, Vector3d theMoveC2)
  /* Calculate the next move and test if there is an obstacle there.
     If there isn't then carry out the move, otherwise issue a
     warning. */
  {
    Point3d nextLoc = possibleMove(theMove);
    if (mm.canMoveTo(nextLoc.x, nextLoc.z)) {    // no obstacle there?
      targetTG.setTransform(t3d);   
         // efficient: t3d is a global set in possibleMove()
      // doMove(theMove, theMoveC2);   // inefficient recalc
      doMoveC2(theMoveC2);
      be.setMove(dir);
    }
    else  // there is an obstacle
      be.bangAlert();  // tell BirdsEye object, so a warning can be shown    
  }  // end of moveBy()



  private Point3d possibleMove(Vector3d theMove)
  /* Calculate the effect of the given translation but
     do not update the object's position until it's been
     tested. */
  { 
    targetTG.getTransform(t3d);   // targetTG is the ViewPlatform's tranform
    toMove.setTranslation(theMove);
    t3d.mul(toMove);
    t3d.get(trans);
    return new Point3d( trans.x, trans.y, trans.z);
  }  // end of possibleMove()


  private void doMove(Vector3d theMove)
  // move the main, forward-facing camera
  {
    targetTG.getTransform(t3d);
    toMove.setTranslation(theMove);
    t3d.mul(toMove);
    targetTG.setTransform(t3d);
  } // end of doMove()


  private void doMoveC2(Vector3d theMoveC2)
  // move the back-facing second camera
  {
    camera2TG.getTransform(t3d);
    toMove.setTranslation(theMoveC2);
    t3d.mul(toMove);
    camera2TG.setTransform(t3d);
  } // end of doMoveC2()


  // ---------------- rotations -----------------------

  private void doRotateY(double radians, int dir)
  // rotate three things
  {
    targetTG.getTransform(t3d);   // rotate main camera
    toRot.rotY(radians);
    t3d.mul(toRot);
    targetTG.setTransform(t3d);

    camera2TG.getTransform(t3d);  // rotate back-facing camera
    t3d.mul(toRot);  // reuse toRot value
    camera2TG.setTransform(t3d);

    be.setRotation(dir);  // rotate bird's eye view
  } 
}
Falls euch immer noch Fragen offen stehen:
Hier ist die Klasse die den KeyBehavior benutzt:
Code:
package Bonus_Game_1;

import javax.swing.*;
import java.awt.*;

import com.sun.j3d.utils.geometry.Sphere;
import com.sun.j3d.utils.image.TextureLoader;
import com.sun.j3d.utils.universe.*;

import javax.media.j3d.*;
import javax.vecmath.*;

public class WrapMaze3D extends JPanel
{
  private static final int PWIDTH = 1450;   // size of panel
  private static final int PHEIGHT = 600; 

  private static final int BOUNDSIZE = 10000;  // larger than world
  private SimpleUniverse su;
  private BranchGroup sceneBG;
  private BoundingSphere bounds;   // for environment nodes

  private PlatformGeometry pg;
  private MazeManager mazeMan;      // maze manager
  private TransformGroup camera2TG; // back-facing camera

  private KeyBehavior g;
  void createStarBackground(BranchGroup bg)
  {
  java.util.Random rand = new java.util.Random();
  float            mag;
  BranchGroup      BGBranch=new BranchGroup();
  Background       BG=new Background();
  Sphere           BGSphere;
 

  PointArray starfield = new PointArray(15000, PointArray.COORDINATES|PointArray.COLOR_3);
  float[] point = new float[3];
  float[] brightness = new float[3];
  for (int i = 0; i < 15000; i++)
     {
     point[0] = (rand.nextInt(2) == 0) ? rand.nextFloat() * -1.0f :rand.nextFloat();
     point[1] = (rand.nextInt(2) == 0) ? rand.nextFloat() * -1.0f :rand.nextFloat();
     point[2] = (rand.nextInt(2) == 0) ? rand.nextFloat() * -1.0f :rand.nextFloat();
     starfield.setCoordinate(i, point);
     mag=(rand.nextFloat()+0.5f)/1.5f;
     brightness[0]=mag;
     brightness[1]=mag;
     brightness[2]=mag;
     starfield.setColor(i, brightness);
     }
  Shape3D StarShape=new Shape3D(starfield);
  StarShape.setAppearance(new Appearance());
  StarShape.getAppearance().setPointAttributes(new PointAttributes(1f,true));
  BGBranch.addChild(StarShape);
  BG.setGeometry(BGBranch);
  BG.setApplicationBounds(new BoundingSphere(new Point3d(),100.0));

  Appearance SphereApp = new Appearance();
  SphereApp.setTexture((new TextureLoader("F:/Rayman/BonusGame_1/Sky.jpg",null)).getTexture());
  SphereApp.setTextureAttributes(new TextureAttributes(TextureAttributes.MODULATE,new Transform3D(),new Color4f(),TextureAttributes.FASTEST));
 
  BGSphere=new Sphere(1.0f,Sphere.GENERATE_NORMALS_INWARD|Sphere.GENERATE_TEXTURE_COORDS,50,SphereApp);
  BGBranch.addChild(BGSphere);

  bg.addChild(BG);
  }

  public WrapMaze3D(MazeManager mm, BirdsEye be, TransformGroup c2TG)
  // construct the scene and the main camera
  {
    mazeMan = mm;       // ref to maze manager
    camera2TG = c2TG;   // ref to second back-facong camera

    setLayout( new BorderLayout() );
    setOpaque( false );
    setPreferredSize( new Dimension(PWIDTH, PHEIGHT));

    GraphicsConfiguration config =
					SimpleUniverse.getPreferredConfiguration();
    Canvas3D canvas3D = new Canvas3D(config);
    add("Center", canvas3D);
    canvas3D.setFocusable(true); 
    canvas3D.requestFocus();
    su = new SimpleUniverse(canvas3D);

    createSceneGraph();
    prepareViewPoint(be);

    su.addBranchGraph( sceneBG );
  } // end of WrapMaze3D()


  void createSceneGraph()
  // initilise the scene 
  { 
    sceneBG = new BranchGroup();
    bounds = new BoundingSphere(new Point3d(0,0,0), BOUNDSIZE); 

    lightScene();     // add the lights  
    TexturedFloor floor = new TexturedFloor();
    sceneBG.addChild( floor.getBG() );
    
    sceneBG.addChild( mazeMan.getMaze() );  // add maze, using MazeManager
    sceneBG.addChild( camera2TG );          // add second camera
    createStarBackground(sceneBG);
    sceneBG.compile();   // fix the scene
  } // end of createSceneGraph()



  private void lightScene()
  // *No* ambient light, 2 directional lights
  {
    Color3f white = new Color3f(0.3f, 0.3f, 0.3f);

    // Set up the ambient light
    AmbientLight ambientLightNode = new AmbientLight(white);
    ambientLightNode.setInfluencingBounds(bounds);
    // sceneBG.addChild(ambientLightNode);   // ambient commented out

    // Set up the directional lights
    Vector3f light1Direction  = new Vector3f(-1.0f, -1.0f, -1.0f);
       // left, down, backwards 
    Vector3f light2Direction  = new Vector3f(1.0f, -1.0f, 1.0f);
       // right, down, forwards

    DirectionalLight light1 = 
            new DirectionalLight(white, light1Direction);
    light1.setInfluencingBounds(bounds);
    sceneBG.addChild(light1);

    DirectionalLight light2 = 
        new DirectionalLight(white, light2Direction);
    light2.setInfluencingBounds(bounds);
    sceneBG.addChild(light2);
  }  // end of lightScene()

  private void prepareViewPoint(BirdsEye be)
  {
    // adjust viewpoint parameters
    View userView = su.getViewer().getView();
    userView.setFieldOfView( Math.toRadians(90.0));  // wider FOV
    // 10 and 0.1; keep ratio between 100-1000
    userView.setBackClipDistance(60);      // can see a long way
    userView.setFrontClipDistance(0.05);   // can see close things

    ViewingPlatform vp = su.getViewingPlatform();

    // add a spotlight and avatar to viewpoint
     pg = new PlatformGeometry();
    pg.addChild( makeSpot() );
    //  pg.addChild(makeAvatar()); // avatar not used here
    vp.setPlatformGeometry( pg );

    // fix starting position and orientation of viewpoint
    TransformGroup steerTG = vp.getViewPlatformTransform();
    initViewPosition(steerTG);

    // set up keyboard controls
    KeyBehavior keybeh = new KeyBehavior(mazeMan, be, camera2TG,pg);
    keybeh.setSchedulingBounds(bounds);
    vp.setViewPlatformBehavior(keybeh);
  } // end of prepareViewPoint()


  private void initViewPosition(TransformGroup steerTG)
  // rotate and move the viewpoint
  {
    Transform3D t3d = new Transform3D();
    steerTG.getTransform(t3d);
    Transform3D toRot = new Transform3D();
    toRot.rotY(-Math.PI);   
    // rotate 180 degrees around Y-axis, so facing along positive z-axis

    t3d.mul(toRot);
	t3d.setTranslation( mazeMan.getMazeStartPosn() );  // place at maze start
    steerTG.setTransform(t3d); 
  }  // end of initViewPosition()


  private SpotLight makeSpot()
  // a spotlight to help the user see in the (relative) darkness
  {
    SpotLight spot = new SpotLight();
    spot.setPosition(0.0f, 0.5f, 0.0f);      // a bit above the user
    spot.setAttenuation(0.0f, 1.2f, 0.0f);   // linear attentuation
    spot.setSpreadAngle( (float)Math.toRadians(30.0));  // smaller angle
    spot.setConcentration(5.0f);            // reduce strength quicker
    spot.setInfluencingBounds(bounds);
    return spot;
  }  // end of makeSpot()


  private TransformGroup makeAvatar()
  {
	TransformGroup U = new TransformGroup();
	
     U.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE);
	 RotationInterpolator rotator1;
     Alpha                rotationAlpha1;
     rotationAlpha1=new Alpha(-1,Alpha.DECREASING_ENABLE|Alpha.INCREASING_ENABLE,0,0,
             9000,3000,500,9000,3000,500);            
     rotator1=new RotationInterpolator(rotationAlpha1,U);
     rotator1.setMinimumAngle((float)Math.toRadians(355f));
     rotator1.setMaximumAngle((float)Math.toRadians(365f));
     rotator1.setSchedulingBounds(bounds);
     U.addChild(rotator1);
	
	Transform3D t = new Transform3D();  
	t.setTranslation(new Vector3f(-0.4f,-0.4f,-0.5f));
	TransformGroup T = new TransformGroup();
	T.setTransform(t);
	U.addChild(T);
	 
	Transform3D t21 = new Transform3D();  
	t21.setTranslation(new Vector3f(0.4f,-0.4f,-0.5f));
	TransformGroup T21 = new TransformGroup();
	T21.setTransform(t21);
	U.addChild(T21);
	
    Transform3D t1 = new Transform3D();
    t1.rotZ(Math.toRadians(70));
    TransformGroup T1 = new TransformGroup(t1);
    T1.addChild( new Rayman_Hand_Left().getChild());  
    T.addChild(T1);
    
    Transform3D t2 = new Transform3D();
    t2.rotZ(Math.toRadians(-70));
    TransformGroup T2 = new TransformGroup(t2);
    T2.addChild( new Rayman_Hand_Right().getChild());  
    T21.addChild(T2);
    
    return U;
  }  
}
Danke schonmal im Voraus
 
Zuletzt bearbeitet:

Neue Beiträge

Zurück