Exemple of collision detection with ghost physics

Hy,



just wanted to share my way to detect collisions, not sure that’s the best one, but can be usefull for someone. If you know a better way, I/m there to learn :wink:



[java]package jme3test.helloworld.collision;



import com.jme3.app.SimpleBulletApplication;

import com.jme3.bullet.collision.shapes.SphereCollisionShape;

import com.jme3.bullet.nodes.PhysicsGhostNode;

import com.jme3.material.Material;

import com.jme3.math.ColorRGBA;

import com.jme3.math.FastMath;

import com.jme3.math.Vector3f;

import com.jme3.system.AppSettings;



public class ThreeBallsCollision extends SimpleBulletApplication{



private PhysicsGhostNode pgnA, pgnB, pgnC;

private int cpt = 0;



public static void main(String[] args){

ThreeBallsCollision app = new ThreeBallsCollision();

AppSettings settings = new AppSettings(true);

settings.setResolution(1280, 720);

settings.setFrameRate(60);

app.setSettings(settings);

//app.setShowSettings(false);

app.start();

}



public void simpleInitApp(){

cam.setLocation(new Vector3f(0,-20,0));

cam.lookAt(Vector3f.ZERO, new Vector3f(0, 1,0));



Material matBlue = new Material(assetManager, “Common/MatDefs/Misc/WireColor.j3md”);

matBlue.setColor(“m_Color”, ColorRGBA.Blue);

Material matRed = new Material(assetManager, “Common/MatDefs/Misc/WireColor.j3md”);

matRed.setColor(“m_Color”, ColorRGBA.Red);

Material matGreen = new Material(assetManager, “Common/MatDefs/Misc/WireColor.j3md”);

matGreen.setColor(“m_Color”, ColorRGBA.Green);



pgnA = new PhysicsGhostNode(new SphereCollisionShape(1));

pgnA.setName(“A (blue)”);

pgnA.attachDebugShape(matBlue);

rootNode.attachChild(pgnA);

getPhysicsSpace().add(pgnA);



pgnB = new PhysicsGhostNode(new SphereCollisionShape(1));

pgnB.setName(“B (red)”);

pgnB.attachDebugShape(matRed);

rootNode.attachChild(pgnB);

getPhysicsSpace().add(pgnB);



pgnC = new PhysicsGhostNode(new SphereCollisionShape(1));

pgnC.setName(“C (green)”);

pgnC.attachDebugShape(matGreen);

rootNode.attachChild(pgnC);

getPhysicsSpace().add(pgnC);

}



public void simpleUpdate(float tpf) {

pgnA.setLocalTranslation(5FastMath.cos(cpttpf), 0, 0);

pgnB.setLocalTranslation(0, 0, 5FastMath.cos(cpttpf));

pgnC.setLocalTranslation(5FastMath.cos(2cpttpf), 0, 5FastMath.sin(cpttpf));



//without this reset the application have a weird behaviour (probably because of FastMath.cos/sin(>> 2xPI))

if((cpt
tpf) > 2*FastMath.PI) cpt=0;



fpsText.setText(cpt+"(f) - "+

"A (blue) overLap : “+pgnA.getOverlappingObjects().toString()+” | "+

"B (red) overLap : “+pgnB.getOverlappingObjects().toString()+” | "+

"C (green) overLap : "+pgnC.getOverlappingObjects().toString());



cpt++;

}

}[/java]