Turning my npc ship to follow the player

Hello,

I’m working on a space simulator. I have the basic player movement done, and have recently started on the AI. While I have been able to set it up so I can spawn a new NPC when the player comes in range of the trigger location, I’m having trouble getting the npc ship to turn towards the player.

The game takes place in a flat surface (X-Y surface). What I need to figure out is how I can determine if I need to turn the NPC ship left or right.\I have the followin values:

  • Location of the NPC ship
  • Current rotation of the NPC ship
  • Location of the player ship
  • Current location of the player ship

Based on these, I need to figure out if I need to turn the NPC ship left or right. Once I have that, I can reuse the existing code I use for turning the player ship for the NPC ship.

I tried figuring it out by doing NPC.getRotation.lookAt(player) and then see if it has turned left or right. But this didn’t get me the result I wanted.

If anyone has any ideas, or sample code I could look at, that would be great

dot product.

Vector3f relPosition = positionOfTheOtherThingYouAreTryingToSteerToward.subtract(myPosition)
float turn = myLeftDirection.dot(relPosition);

myLeftDirection = myDirection.cross(upVector)

Edit: could actually be the right direction. Adjust accordingly.

ok, so I need myLeftDirection as a Vector3f. I currently have my corrent location, as a Vector3f and my current rotation, as a quaternion. If I want to go from the quaternion rotation to the direction as a Vector3f, how would that happen?

@ractoc said: ok, so I need myLeftDirection as a Vector3f. I currently have my corrent location, as a Vector3f and my current rotation, as a quaternion. If I want to go from the quaternion rotation to the direction as a Vector3f, how would that happen?

Since you are in x,y space… what do you consider “forward” to be relative to the ship? Unit X or unit y?

Also, wtf… how are you moving your ships if you don’t know what direction they are facing? :slight_smile:

yay, managed to fix it, with a lot of help. Thanx Paul for hanging in there.

I did a bit of looking at my actual movement code, which helped as well, here’s the end result:
[java]
LocationComponent clc = componentStorages.loadComponentForEntity(controlledEntity.getId(), LocationComponent.class);
Vector3f relPosition = clc.getTranslation().subtract(slc.getTranslation()).normalize();
Vector3f myLeftDirection = slc.getRotation().mult(Vector3f.UNIT_Z).normalizeLocal().cross(Vector3f.UNIT_Y);
float turn = myLeftDirection.dot(relPosition);
if (turn < 0) {
rotateLeft();
} else if (turn > 0) {
rotateRight();
} else {
stopRotating();
}
[/java]

This makes it so the enemy ship is always following the player, now to put some actual movement in there instead of just rotating. But compared to this, that should be easy…

The above math implies that you are actually in x,z space, ie: y is up.