# How can I make a unit fire in one direction while still moving in another?

My code ALMOST works perfectly but for some reason when I give my unit the command to fire while it’s already moving, the first shot will fly off in the direction It was moving. (the following shots work fine, even while still moving).

I’m new to unity so i’m confused because everything seems like it should work here.

Here’s the code. Any help is appreciated!

``````using UnityEngine;
using UnityEngine.AI;
using System;

public class PlayerControls : MonoBehaviour {

public float moveSpeed;      // How fast this unit moves per frame.
public Transform firePoint;  // Where the bullet is fired from.
public GameObject bullet;    // Reference to the pre-created object called bullet.

NavMeshAgent thisUnit;       // This unit's NavMeshAgent
Vector3 clickLocation;       // The last clicked location.
Rigidbody rigidBody;         // Reference to the Rigidbody used by this unit.
LayerMask floorMask;         // The location of the floor.
float camRayLength;          // How far the camera will look when searching for the floor.

// Initialization of variables upon creation of this script.
void Awake()
{
rigidBody = GetComponent<Rigidbody>();
thisUnit = GetComponent<NavMeshAgent>();
camRayLength = 150f;
}

// Game mainloop. Contains all player Inputs.
private void Update()
{
// When the player right clicks, moves the player.
if (Input.GetKey("mouse 1"))
{
clickLocation = FindMouse();
Turn(clickLocation);
Move(clickLocation);
}

//Fires a bullet when you push down the Q button.
if (Input.GetKeyDown(KeyCode.Q))
{
Turn(FindMouse());
Shoot();
}
}

// Rotates the player to a certain direction
void Turn(Vector3 targetRotation)
{
targetRotation = targetRotation - transform.position;
targetRotation.y = 0f;

Quaternion newRotation = Quaternion.LookRotation(targetRotation);
rigidBody.MoveRotation(newRotation);
}

// Finds the location of the mouse in relation to the ground.
public Vector3 FindMouse()
{
Ray camRay = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit floorHit;

Physics.Raycast(camRay, out floorHit, camRayLength, floorMask);
Vector3 mouseLocation = floorHit.point;
mouseLocation.y = 0f;
return mouseLocation;
}

// Moves the player forwards by one unit of move speed.
void Move(Vector3 target)
{
thisUnit.SetDestination(target);
}

// Creates a bullet, sets it's start position and start rotation.
void Shoot()
{
Instantiate(bullet, firePoint.position, firePoint.rotation);
}
}
``````

Good day.

In Void turn(), are you sure this is correct?

`````` targetRotation = targetRotation - transform.position;
``````

I supouse you wanted to do this

`````` targetRotation = targetPosition - transform.position;
``````

Bye!!