I am trying to create a lser beam using a simple glowing cylinder put into the world for a short time.
I manages to get nearly everything right but somehow i can’t wrap my head arround how to rotate and move the cylinder so that it points the right way.
With the code i got so far i can determine where i click, calculate the point on the ground plane to get the direktion and now want to place the cylinder so that it shoots from my player towards this spot (horizontal to the groundplane). My player origin is at the groundplane, so i thought i can just moce the cylinder to the players origin, rotate it towards the point and move it half its length forward. When i shoot along the z axis it looks fine, but when i shoot somewhere else the laser is off its target. Things get even stranger when i fire behind the player (have a third person view with a bit of floor behind player visible).
My code so far:
[java]
public static final Quaternion PITCH090 = new Quaternion().fromAngleAxis(FastMath.PI / 2, new Vector3f(0, 1, 0));
public void onAction(String name, boolean isPressed, float tpf) {
if (name.equals("Shoot") && isPressed) {
if (laserBeam == null) {
CollisionResults results = new CollisionResults();
Vector2f click2d = inputManager.getCursorPosition();
Vector3f click3d = cam.getWorldCoordinates(new Vector2f(click2d.x, click2d.y), 0f).clone();
Vector3f dir = cam.getWorldCoordinates(new Vector2f(click2d.x, click2d.y), 1f).subtractLocal(click3d).normalizeLocal();
Ray ray = new Ray(click3d, dir);
Plane ground = new Plane(Vector3f.UNIT_Y, 0);
Vector3f groundpoint = new Vector3f();
ray.intersectsWherePlane(ground, groundpoint);
Sphere help = new Sphere(8, 8, 0.2f);
helper = new Geometry("helper", help);
Material mathelper = mat.clone();
mathelper.setColor("Color", ColorRGBA.Red);
mathelper.setColor("GlowColor", ColorRGBA.Magenta);
helper.setMaterial(mathelper);
helper.center().move(groundpoint);
rootNode.attachChild(helper);
Cylinder laser = new Cylinder(4, 8, 0.02f, 100);
laserBeam = new Geometry("laserbeam", laser);
Material matlaser = mat.clone();
matlaser.setColor("Color", ColorRGBA.Orange);
matlaser.setColor("GlowColor", ColorRGBA.Red);
laserBeam.setMaterial(matlaser);
laserBeam.center();
laserBeam.move(player.getLocalTranslation());
laserBeam.rotate(player.getLocalRotation());
Quaternion rotation = laserBeam.getLocalRotation();
rotation.lookAt(groundpoint, Vector3f.UNIT_Y);
rotation = rotation.mult(PITCH090);
laserBeam.rotate(rotation);
laserBeam.move(new Vector3f(0, 3, 0));
laserBeam.move(laserBeam.getLocalRotation().mult(new Vector3f(0, 0, 50)));
rootNode.attachChild(laserBeam);
laserlifetime = lasermaxlifetime;
}
}
}
@Override
public void simpleUpdate(float tpf) {
if (laserlifetime 0 && laserBeam != null) {
laserlifetime -= tpf;
}
}
[/java]
I know it looks a bit messy, but thats from trying to figure it out, once i know how to do it i am going to tidy it up.
Anyone got a clue what i am doing wrong ?