### Author Topic: turret aiming on target  (Read 933 times)

#### Dinin

• byte
• Posts: 28
##### turret aiming on target
« on: November 17, 2012, 04:09:16 pm »
Hi !

I wanted a turret (mounted on a spaceship) to aim at a target.
So i have a turretBody only rotating around y axis and a turretBarrel rotating around x axis.

I tried to do it so:
Code: [Select]
`public void targetAt(){ // Targetdirection SimpleVector directionD = target.getTransformedCenter().calcSub(turretBody.getTransformedCenter()).normalize(); //The object's initial direction SimpleVector directionI = turretBarrel.getWorldTransformation().getYAxis().normalize(); //Axis to rotate around SimpleVector axis = new SimpleVector( directionD.calcCross( directionI ) ).normalize(); float turnrate = .03f; if (axis.x < 0) turretBarrel.rotateX(-turnrate); else turretBarrel.rotateX(turnrate); if (axis.z < 0) turretBody.rotateY(-turnrate); else turretBody.rotateY(turnrate); }`
Works fine if ship is not rotating.
But when the ship rotates at a specific position the turret aims exactly in the direction away from target. I think because the cross product of the vectors changes direction on different angle of the vectors.
But how can i get always the right rotateaxis ?

Here the complete code with objectgeneration:
Code: [Select]
`public void init(){ world.removeAll(); createObjects(); } public void gameloop(){ targetAt(); ship.rotateX(.005f); target.translate(1 * translatedirection,0,0); if (Math.abs(target.getTransformedCenter().x) > 80) translatedirection *= -1; } public void createObjects(){ target = Primitives.getBox(5, 3); target.setAdditionalColor(RGBColor.BLUE); target.translate(0,-40,0); world.addObject(target); ship = Primitives.getBox(7, 1); ship.setAdditionalColor(RGBColor.WHITE); ship.translate(50,100,0); world.addObject(ship); turretBody =  Primitives.getBox(3, 1); turretBody.setAdditionalColor(RGBColor.GREEN); turretBody.translate(0,-10,0); world.addObject(turretBody); turretBarrel = Primitives.getBox(1, 7); turretBarrel.build(); turretBarrel.rotateX(Manager.degreesToRadians(180)); turretBarrel.setRotationPivot(new SimpleVector(0,-7,0)); turretBarrel.setAdditionalColor(RGBColor.RED); turretBarrel.translate(0,5,0); world.addObject(turretBarrel); ship.addChild(turretBody); turretBody.addChild(turretBarrel); ship.rotateX(Manager.degreesToRadians(90)); } public void targetAt(){ // Targetdirection SimpleVector directionD = target.getTransformedCenter().calcSub(turretBody.getTransformedCenter()).normalize(); //The object's initial direction: SimpleVector directionI = turretBarrel.getWorldTransformation().getYAxis().normalize(); //Axis to rotate around should be: SimpleVector axis = new SimpleVector( directionD.calcCross( directionI ) ).normalize(); float turnrate = .03f; if (axis.x < 0) turretBarrel.rotateX(-turnrate); else turretBarrel.rotateX(turnrate); if (axis.z < 0) turretBody.rotateY(-turnrate); else turretBody.rotateY(turnrate); }`
Thanks for any help.
Greetings
Dinin