Move character automacally on land

Hallo,I wanna that an oto character walks alon (no by key) in a physics world. How can change the simpleUpdate() for this ??
In this code the problem is that my oto doesn’t WALKS but just shift! I wanna WALK and SHIFT on the land …:frowning:

[java]
import com.jme3.animation.AnimChannel;
import com.jme3.animation.AnimControl;
import com.jme3.animation.AnimEventListener;
import com.jme3.animation.LoopMode;
import com.jme3.app.SimpleApplication;
import com.jme3.asset.plugins.ZipLocator;
import com.jme3.bullet.BulletAppState;
import com.jme3.bullet.PhysicsSpace;
import com.jme3.bullet.collision.PhysicsCollisionEvent;
import com.jme3.bullet.collision.PhysicsCollisionListener;
import com.jme3.bullet.collision.shapes.CapsuleCollisionShape;
import com.jme3.bullet.collision.shapes.SphereCollisionShape;
import com.jme3.bullet.control.CharacterControl;
import com.jme3.bullet.control.RigidBodyControl;
import com.jme3.bullet.util.CollisionShapeFactory;
import com.jme3.effect.ParticleEmitter;
import com.jme3.effect.ParticleMesh.Type;
import com.jme3.effect.shapes.EmitterSphereShape;
import com.jme3.export.binary.BinaryExporter;
import com.jme3.export.binary.BinaryImporter;
import com.jme3.input.ChaseCamera;
import com.jme3.input.KeyInput;
import com.jme3.input.controls.ActionListener;
import com.jme3.input.controls.KeyTrigger;
import com.jme3.light.DirectionalLight;
import com.jme3.material.Material;
import com.jme3.math.ColorRGBA;
import com.jme3.math.Vector2f;
import com.jme3.math.Vector3f;
import com.jme3.post.FilterPostProcessor;
import com.jme3.post.filters.BloomFilter;
import com.jme3.renderer.Camera;
import com.jme3.renderer.queue.RenderQueue.ShadowMode;
import com.jme3.scene.Geometry;
import com.jme3.scene.Node;
import com.jme3.scene.Spatial;
import com.jme3.scene.shape.Box;
import com.jme3.scene.shape.Sphere;
import com.jme3.scene.shape.Sphere.TextureMode;
import com.jme3.terrain.geomipmap.TerrainLodControl;
import com.jme3.terrain.geomipmap.TerrainQuad;
import com.jme3.terrain.heightmap.AbstractHeightMap;
import com.jme3.terrain.heightmap.ImageBasedHeightMap;
import com.jme3.texture.Texture;
import com.jme3.texture.Texture.WrapMode;
import com.jme3.util.SkyFactory;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**

  • A walking animated character followed by a 3rd person camera on a terrain with LOD.
  • @author normenhansen
    */

/**

  • A walking animated character followed by a 3rd person camera on a terrain with LOD.

  • @author normenhansen
    */
    public class TestWalkingChar extends SimpleApplication implements ActionListener, PhysicsCollisionListener, AnimEventListener {

    private BulletAppState bulletAppState;
    //character
    CharacterControl character;
    Node model;
    //another character
    CharacterControl charactInMove;
    Node modelInMove;
    AnimControl control;
    AnimChannel chan;
    // static float passi=-90;
    static float walkTimeRemaining = 5f; // seconds
    //temp vectors
    Vector3f walkDirection = new Vector3f();
    Vector3f walk = new Vector3f();
    //terrain
    TerrainQuad terrain;
    RigidBodyControl terrainPhysicsNode;
    //Materials
    Material matRock;
    Material matBullet;
    //animation
    AnimChannel animationChannel;
    AnimChannel shootingChannel;
    AnimControl animationControl;

    float airTime = 0;
    //camera
    boolean left = false, right = false, up = false, down = false;
    ChaseCamera chaseCam;
    //bullet
    Sphere bullet;
    SphereCollisionShape bulletCollisionShape;
    //explosion
    ParticleEmitter effect;
    //brick wall
    Box brick;
    float bLength = 0.8f;
    float bWidth = 0.4f;
    float bHeight = 0.4f;
    FilterPostProcessor fpp;
    private static int i;

    public static void main(String[] args) {
    TestWalkingChar app = new TestWalkingChar();
    app.start();
    i=0;
    while(i<10000){
    i++;
    }

    }

    @Override
    public void simpleInitApp() {
    bulletAppState = new BulletAppState();
    bulletAppState.setThreadingType(BulletAppState.ThreadingType.PARALLEL);
    stateManager.attach(bulletAppState);

     setupKeys();
     prepareBullet();
     prepareEffect();
     createLight();
     createSky();
     createTerrain();
     createWall();
     try {
     	createCharacter();
     } catch (IOException e) {
     	// TODO Auto-generated catch block
     	e.printStackTrace();
     }
     setupChaseCamera();
     setupAnimationController();
     setupFilter();
    

    }

    private void setupFilter() {
    FilterPostProcessor fpp = new FilterPostProcessor(assetManager);
    BloomFilter bloom = new BloomFilter(BloomFilter.GlowMode.Objects);
    fpp.addFilter(bloom);
    viewPort.addProcessor(fpp);
    }

    private PhysicsSpace getPhysicsSpace() {
    return bulletAppState.getPhysicsSpace();
    }

    private void setupKeys() {

     inputManager.addMapping("wireframe", new KeyTrigger(KeyInput.KEY_T));
    
     inputManager.addMapping("CharLeft", new KeyTrigger(KeyInput.KEY_A));
     inputManager.addMapping("CharRight", new KeyTrigger(KeyInput.KEY_D));
     inputManager.addMapping("CharUp", new KeyTrigger(KeyInput.KEY_W));
     inputManager.addMapping("CharDown", new KeyTrigger(KeyInput.KEY_S));
     inputManager.addMapping("jump", new KeyTrigger(KeyInput.KEY_SPACE));
    
     inputManager.addListener(this, "CharLeft");
     inputManager.addListener(this, "CharRight");
     inputManager.addListener(this, "CharUp");
     inputManager.addListener(this, "CharDown");
     inputManager.addListener(this, "jump");
    

    }

    private void createWall() {
    float xOff = -144;
    float zOff = -40;
    float startpt = bLength / 4 - xOff;
    float height = 6.1f;
    brick = new Box(Vector3f.ZERO, bLength, bHeight, bWidth);
    brick.scaleTextureCoordinates(new Vector2f(1f, .5f));
    for (int j = 0; j < 15; j++) {
    for (int i = 0; i < 4; i++) {
    Vector3f vt = new Vector3f(i * bLength * 2 + startpt, bHeight + height, zOff);
    addBrick(vt);
    }
    startpt = -startpt;
    height += 1.01f * bHeight;
    }
    }

    private void addBrick(Vector3f ori) {
    Geometry reBoxg = new Geometry(“brick”, brick);
    reBoxg.setMaterial(matBullet);
    reBoxg.setLocalTranslation(ori);
    reBoxg.addControl(new RigidBodyControl(1.5f));
    reBoxg.setShadowMode(ShadowMode.CastAndReceive);
    this.rootNode.attachChild(reBoxg);
    this.getPhysicsSpace().add(reBoxg);
    }

    private void prepareBullet(){
    bullet = new Sphere(32, 32, 0.4f, true, false);
    bullet.setTextureMode(TextureMode.Projected);
    bulletCollisionShape = new SphereCollisionShape(0.4f);
    matBullet = new Material(getAssetManager(), “Common/MatDefs/Misc/Unshaded.j3md”);
    matBullet.setColor(“Color”, ColorRGBA.Green);
    matBullet.setColor(“GlowColor”, ColorRGBA.Green);
    getPhysicsSpace().addCollisionListener(this);
    }

    private void prepareEffect() {
    int COUNT_FACTOR = 1;
    float COUNT_FACTOR_F = 1f;
    effect = new ParticleEmitter(“Flame”, Type.Triangle, 32 * COUNT_FACTOR);
    effect.setSelectRandomImage(true);
    effect.setStartColor(new ColorRGBA(1f, 0.4f, 0.05f, (float) (1f / COUNT_FACTOR_F)));
    effect.setEndColor(new ColorRGBA(.4f, .22f, .12f, 0f));
    effect.setStartSize(1.3f);
    effect.setEndSize(2f);
    effect.setShape(new EmitterSphereShape(Vector3f.ZERO, 1f));
    effect.setParticlesPerSec(0);
    effect.setGravity(0, -30 , 0);
    effect.setLowLife(.4f);
    effect.setHighLife(.5f);
    effect.setInitialVelocity(new Vector3f(0, 7, 0));
    effect.setVelocityVariation(1f);
    effect.setImagesX(2);
    effect.setImagesY(2);
    Material mat = new Material(assetManager, “Common/MatDefs/Misc/Particle.j3md”);
    mat.setTexture(“Texture”, assetManager.loadTexture(“Effects/Explosion/flame.png”));
    effect.setMaterial(mat);
    // effect.setLocalScale(100);
    rootNode.attachChild(effect);
    }

    private void createCharacter() throws IOException {
    CapsuleCollisionShape capsule = new CapsuleCollisionShape(3f, 4f);
    character = new CharacterControl(capsule, 0.01f);
    model = (Node) assetManager.loadModel(“Models/Sinbad/Sinbad.mesh.xml”);
    //model.setLocalScale(0.5f);
    model.addControl(character);
    character.setPhysicsLocation(new Vector3f(-100, 20, -100));
    rootNode.attachChild(model);
    getPhysicsSpace().add(character);

     //--------------------------- CHARACTER TO MOVE 
    
     CapsuleCollisionShape capsule_2 = new CapsuleCollisionShape(3f, 4f);
     charactInMove = new CharacterControl(capsule_2, 0.01f);
     modelInMove = (Node) assetManager.loadModel("Models/Oto/Oto.mesh.xml");
     modelInMove.addControl(charactInMove);
     charactInMove.setPhysicsLocation(new Vector3f(-90, 20, -100));
     rootNode.attachChild(modelInMove);
     getPhysicsSpace().add(charactInMove);
     control = modelInMove.getControl(AnimControl.class);
      chan = control.createChannel();
    

    }

    private void createLight(){
    Vector3f direction = new Vector3f(-0.1f, -0.7f, -1).normalizeLocal();
    DirectionalLight dl = new DirectionalLight();
    dl.setDirection(direction);
    dl.setColor(new ColorRGBA(1f, 1f, 1f, 1.0f));
    rootNode.addLight(dl);
    }

    private void createSky() {
    rootNode.attachChild(SkyFactory.createSky(assetManager, “Textures/Sky/Bright/BrightSky.dds”, false));
    }

    private void createTerrain() {
    //floor
    matRock = new Material(assetManager, “Common/MatDefs/Terrain/TerrainLighting.j3md”);
    matRock.setBoolean(“useTriPlanarMapping”, false);
    matRock.setBoolean(“WardIso”, true);
    // Type of structur floor
    matRock.setTexture(“AlphaMap”, assetManager.loadTexture(“Textures/Terrain/splat/alphamap2.png”));
    //heigth floor (example just horizon or witn mountain ecc)
    Texture heightMapImage = assetManager.loadTexture(“Textures/Terrain/splat/fortress512.png”);
    //type of grass
    Texture grass = assetManager.loadTexture(“Textures/Terrain/splat/grass.jpg”);
    grass.setWrap(WrapMode.Repeat);
    matRock.setTexture(“DiffuseMap”, grass);
    matRock.setFloat(“DiffuseMap_0_scale”, 64);

     Texture dirt = assetManager.loadTexture("Textures/Terrain/splat/dirt.jpg");
     dirt.setWrap(WrapMode.Repeat);
     matRock.setTexture("DiffuseMap_1", dirt);
     matRock.setFloat("DiffuseMap_1_scale", 16);
     
     Texture rock = assetManager.loadTexture("Textures/Terrain/splat/road.jpg");
     rock.setWrap(WrapMode.Repeat);
     matRock.setTexture("DiffuseMap_2", rock);
     matRock.setFloat("DiffuseMap_2_scale", 128);
     
     Texture normalMap0 = assetManager.loadTexture("Textures/Terrain/splat/grass_normal.jpg");
     normalMap0.setWrap(WrapMode.Repeat);
     
     Texture normalMap1 = assetManager.loadTexture("Textures/Terrain/splat/dirt_normal.png");
     normalMap1.setWrap(WrapMode.Repeat);
     
     Texture normalMap2 = assetManager.loadTexture("Textures/Terrain/splat/road_normal.png");
     normalMap2.setWrap(WrapMode.Repeat);
    
     matRock.setTexture("NormalMap", normalMap0);
     matRock.setTexture("NormalMap_1", normalMap2);
     matRock.setTexture("NormalMap_2", normalMap2);
    
     AbstractHeightMap heightmap = null;
     try {
         heightmap = new ImageBasedHeightMap(heightMapImage.getImage(), 0.25f);
         heightmap.load();
    
     } catch (Exception e) {
         e.printStackTrace();
     }
    
     terrain = new TerrainQuad("terrain", 65, 513, heightmap.getHeightMap());
     
     List&lt;Camera&gt; cameras = new ArrayList&lt;Camera&gt;();
     cameras.add(getCamera());
     TerrainLodControl control = new TerrainLodControl(terrain, cameras);
     terrain.addControl(control);
     terrain.setMaterial(matRock);
     terrain.setLocalScale(new Vector3f(2, 2, 2));
    
     terrainPhysicsNode = new RigidBodyControl(CollisionShapeFactory.createMeshShape(terrain), 0);
     terrain.addControl(terrainPhysicsNode);
     rootNode.attachChild(terrain);
     getPhysicsSpace().add(terrainPhysicsNode);
    

    }

    private void setupChaseCamera() {
    flyCam.setEnabled(false);
    chaseCam = new ChaseCamera(cam, model, inputManager);
    }

    private void setupAnimationController() {
    animationControl = model.getControl(AnimControl.class);
    animationControl.addListener(this);
    animationChannel = animationControl.createChannel();
    }

    @Override
    public void simpleUpdate(float tpf) {
    Vector3f camDir = cam.getDirection().clone().multLocal(0.1f);
    Vector3f camLeft = cam.getLeft().clone().multLocal(0.1f);
    camDir.y = 0;
    camLeft.y = 0;
    walkDirection.set(0, 0, 0);
    if (left) {
    walkDirection.addLocal(camLeft);
    }
    if (right) {
    walkDirection.addLocal(camLeft.negate());
    }
    if (up) {
    walkDirection.addLocal(camDir);
    }
    if (down) {
    walkDirection.addLocal(camDir.negate());
    }
    if (!character.onGround()) {
    airTime = airTime + tpf;
    } else {
    airTime = 0;
    }
    if (walkDirection.length() == 0) {
    if (!“IdleTop”.equals(animationChannel.getAnimationName())) {
    animationChannel.setAnim(“IdleTop”, 1f);
    }
    } else {
    character.setViewDirection(walkDirection);
    if (airTime > .3f) {
    if (!“IdleTop”.equals(animationChannel.getAnimationName())) {
    animationChannel.setAnim(“IdleTop”);
    }
    } else if (!“RunBase”.equals(animationChannel.getAnimationName())) {
    animationChannel.setAnim(“RunBase”, 0.7f);
    }
    }
    character.setWalkDirection(walkDirection);

     if (walkTimeRemaining &gt; 0) {
        walk.z = 0.01f;
        walkTimeRemaining -= tpf;
    }
    

// chan.setAnim(“Walk”); //???
charactInMove.setWalkDirection(walk);
}

public void onAction(String binding, boolean value, float tpf) {
    if (binding.equals("CharLeft")) {
        if (value) {
            left = true;
        } else {
            left = false;
        }
    } else if (binding.equals("CharRight")) {
        if (value) {
            right = true;
        } else {
            right = false;
        }
    } else if (binding.equals("CharUp")) {
        if (value) {
            up = true;
        } else {
            up = false;
        }
    } else if (binding.equals("CharDown")){
        if (value) {
            down = true;
        } else {
            down = false;
        }
    }else if (binding.equals("jump") &amp;&amp; !value) {
    	 animationChannel.setAnim("SliceHorizontal", 0.1f);
    }
}

/*
private void bulletControl() {
shootingChannel.setAnim(“Dodge”, 0.1f);
shootingChannel.setLoopMode(LoopMode.DontLoop);
Geometry bulletg = new Geometry(“bullet”, bullet);
bulletg.setMaterial(matBullet);
bulletg.setShadowMode(ShadowMode.CastAndReceive);
bulletg.setLocalTranslation(character.getPhysicsLocation().add(cam.getDirection().mult(5)));
RigidBodyControl bulletControl = new BombControl(bulletCollisionShape, 1);
bulletControl.setCcdMotionThreshold(0.1f);
bulletControl.setLinearVelocity(cam.getDirection().mult(80));
bulletg.addControl(bulletControl);
rootNode.attachChild(bulletg);
getPhysicsSpace().add(bulletControl);
}

/
/

public void collision(PhysicsCollisionEvent event) {
if (event.getObjectA() instanceof BombControl) {
final Spatial node = event.getNodeA();
effect.killAllParticles();
effect.setLocalTranslation(node.getLocalTranslation());
effect.emitAllParticles();
} else if (event.getObjectB() instanceof BombControl) {
final Spatial node = event.getNodeB();
effect.killAllParticles();
effect.setLocalTranslation(node.getLocalTranslation());
effect.emitAllParticles();
}
}
*/

@Override
public void onAnimChange(AnimControl arg0, AnimChannel arg1, String arg2) {
	// TODO Auto-generated method stub
}

@Override
public void onAnimCycleDone(AnimControl arg0, AnimChannel arg1, String arg2) {
	// TODO Auto-generated method stub
	
}

@Override
public void collision(PhysicsCollisionEvent arg0) {
	// TODO Auto-generated method stub
	
}

}
[/java]

(1) This is a repeat of a previous post in the MonkeyZone forum. Rule #7 of “How to Get Answers” is “Don’t post the same question repeatedly”.

(2) Your code has so many features, it takes a long time to analyze. When asking for support you should try to provide the simplest code which demonstrates the issue you are concerned with.

Here is a simpler app (based on yours) which walks a character 30 units in the x-direction:
[java]
package baseCharacter;

import com.jme3.animation.AnimChannel;
import com.jme3.animation.AnimControl;
import com.jme3.app.SimpleApplication;
import com.jme3.bullet.BulletAppState;
import com.jme3.bullet.PhysicsSpace;
import com.jme3.bullet.collision.shapes.CapsuleCollisionShape;
import com.jme3.bullet.control.CharacterControl;
import com.jme3.bullet.control.RigidBodyControl;
import com.jme3.bullet.util.CollisionShapeFactory;
import com.jme3.input.ChaseCamera;
import com.jme3.light.DirectionalLight;
import com.jme3.material.Material;
import com.jme3.math.ColorRGBA;
import com.jme3.math.Vector3f;
import com.jme3.scene.Node;
import com.jme3.terrain.geomipmap.TerrainQuad;
import com.jme3.terrain.heightmap.AbstractHeightMap;
import com.jme3.terrain.heightmap.ImageBasedHeightMap;
import com.jme3.texture.Texture;
import com.jme3.util.SkyFactory;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**

  • A walking animated character followed by a 3rd person camera on a terrain

  • with LOD.
    */
    public class Main
    extends SimpleApplication {

    private BulletAppState bulletAppState;
    //character
    private CharacterControl charactInMove;
    private Node model;
    AnimChannel chan;
    //terrain
    private TerrainQuad terrain;
    private RigidBodyControl terrainPhysicsNode;
    //animation
    private AnimChannel animationChannel;
    private AnimControl animationControl;
    private float airTime = 0;
    private float startX = -100;
    //camera
    ChaseCamera chaseCam;
    static float walkTimeRemaining = 5f; // seconds

    public static void main(String[] args) {
    Logger.getLogger("").setLevel(Level.SEVERE);
    Main app = new Main();
    app.setShowSettings(false);
    app.start();
    }

    @Override
    public void simpleInitApp() {
    bulletAppState = new BulletAppState();
    stateManager.attach(bulletAppState);

     createLight();
     createSky();
     createTerrain();
     try {
         createCharacter();
     } catch (IOException e) {
     }
     setupChaseCamera();
     setupAnimationController();
    

    }

    private PhysicsSpace getPhysicsSpace() {
    return bulletAppState.getPhysicsSpace();
    }

    private void createCharacter() throws IOException {
    CapsuleCollisionShape capsule = new CapsuleCollisionShape(3f, 4f);
    charactInMove = new CharacterControl(capsule, 0.01f);
    model = (Node) assetManager.loadModel(“Models/Sinbad/Sinbad.mesh.xml”);
    model.addControl(charactInMove);
    charactInMove.setPhysicsLocation(new Vector3f(startX, 30, -100));
    rootNode.attachChild(model);
    getPhysicsSpace().add(charactInMove);
    }

    private void createLight() {
    Vector3f direction = new Vector3f(-0.1f, -0.7f, -1).normalizeLocal();
    DirectionalLight dl = new DirectionalLight();
    dl.setDirection(direction);
    dl.setColor(ColorRGBA.White);
    rootNode.addLight(dl);
    }

    private void createSky() {
    rootNode.attachChild(SkyFactory.createSky(assetManager,
    “Textures/Sky/Bright/BrightSky.dds”, false));
    }

    private void createTerrain() {
    Material yellow = new Material(assetManager,
    “Common/MatDefs/Light/Lighting.j3md”);
    yellow.setBoolean(“UseMaterialColors”, true);
    yellow.setColor(“Diffuse”, ColorRGBA.Yellow);

     //height floor (example just horizon or with mountain etc)
     Texture heightMapImage = assetManager.loadTexture(
             "Textures/Terrain/splat/fortress512.png");
     AbstractHeightMap heightmap = null;
     try {
         heightmap =
                 new ImageBasedHeightMap(heightMapImage.getImage(), 0.25f);
         heightmap.load();
    
     } catch (Exception e) {
     }
    
     terrain = new TerrainQuad("terrain", 65, 513, heightmap.getHeightMap());
    
     terrain.setMaterial(yellow);
     terrain.setLocalScale(new Vector3f(2, 2, 2));
     terrainPhysicsNode = new RigidBodyControl(CollisionShapeFactory.createMeshShape(terrain), 0);
     terrain.addControl(terrainPhysicsNode);
     rootNode.attachChild(terrain);
     getPhysicsSpace().add(terrainPhysicsNode);
    

    }

    private void setupChaseCamera() {
    flyCam.setEnabled(false);
    chaseCam = new ChaseCamera(cam, model, inputManager);
    }

    private void setupAnimationController() {
    animationControl = model.getControl(AnimControl.class);
    animationChannel = animationControl.createChannel();
    }

    @Override
    public void simpleUpdate(float tpf) {
    Vector3f walk = new Vector3f();
    float currentX = charactInMove.getPhysicsLocation().x;
    System.out.printf(“X = %f\n”, currentX);
    if (currentX < startX + 30) {
    walk.x = 0.2f;
    }

     if (!charactInMove.onGround()) {
         airTime = airTime + tpf;
     } else {
         airTime = 0;
     }
     if (walk.length() == 0) {
         if (!"IdleTop".equals(animationChannel.getAnimationName())) {
             animationChannel.setAnim("IdleTop", 1f);
         }
     } else {
         charactInMove.setViewDirection(walk);
         if (airTime &gt; .3f) {
             if (!"IdleTop".equals(animationChannel.getAnimationName())) {
                 animationChannel.setAnim("IdleTop");
             }
         } else if (!"RunBase".equals(animationChannel.getAnimationName())) {
             animationChannel.setAnim("RunBase", 0.7f);
         }
     }
     charactInMove.setWalkDirection(walk);
    

    }
    }
    [/java]

1 Like

Thanks very much for the help, and scuse me … :slight_smile: Just onother question, I don’t understand what is the function of airtime and tpf and what is the initial value of this ??

[java]
//…

if (!charactInMove.onGround()) {
        airTime = airTime + tpf;
    } else {
        airTime = 0;
    }

//…
[/java]

airtime appears to keep track of how long the character has been in the air.
tpf is the number of seconds since the previous update