I have a strange problem that I will try and explain as good as I can.
I have attached the camera to the player, everything works well with walking around, jumping and looking in all directions.
Now I am trying to implement shooting bullets from the gun (the cube is the substitute gun).
Doing this I noticed that the camera doesn’t seem to be directly on the player somehow.
The player should be standing between the two snowmen (which should make the camera also stand there), as the position is set to be there.
This becomes apparent when trying to shoot a bullet (snowmen are substitute bullets). The bullets do not move at all when being shot at the moment and no matter which side the camera is looking at, it always spawns the bullet in that same position (See picture number two for position).
I have a hard time finding out why the camera doesn’t position itself directly on the players position.
Player starts in wrong position:
Player shoots a bullet:
Camera class:
class FirstPersonCamera
{
private Vector3 position;
private Vector3 rotation;
private Vector3 lookAt;
private Vector3 up = Vector3.Up;
private Vector3 forward = Vector3.Forward;
private Vector3 offset = new Vector3(0, 0.45f, 0);
private Matrix projection;
private Entity attachedTo;
public Vector3 Offset { get => offset; }
public Vector3 LookAt { get => lookAt; }
public Vector3 Up { get => up; }
public Vector3 Direction { get => forward; }
public Vector3 Position
{
get { return position; }
set
{
position = value;
UpdateLookAt();
}
}
public Vector3 Rotation
{
get { return rotation; }
set
{
rotation = value;
UpdateLookAt();
}
}
public Matrix Projection { get => projection; protected set => projection = value; }
public Matrix View { get => Matrix.CreateLookAt(position, lookAt, up); }
public Matrix World { get => Matrix.CreateWorld(lookAt, forward, up); }
public FirstPersonCamera(GraphicsDevice graphicsDevice, Vector3 position, Vector3 rotation)
{
projection = Matrix.CreatePerspectiveFieldOfView((float)(Math.PI / 3), graphicsDevice.Viewport.AspectRatio, 0.01f, 1000.0f);
MoveTo(position, rotation);
}
public void Update(GameTime gameTime)
{
MoveTo(attachedTo.Position + offset, attachedTo.Rotation);
}
public void AttachTo(Entity entity)
{
attachedTo = entity;
}
private void MoveTo(Vector3 position, Vector3 rotation)
{
Position = position;
Rotation = rotation;
}
private void UpdateLookAt()
{
Matrix rotationMatrix = Matrix.CreateRotationX(rotation.X) * Matrix.CreateRotationY(rotation.Y) * Matrix.CreateRotationZ(rotation.Z);
Vector3 lookAtOffset = Vector3.Transform(Vector3.UnitZ, rotationMatrix);
lookAt = position + lookAtOffset;
}
}