I’m creating a top down shooter. In my update function, I control the camera and player movement. I also have a function that shoots. However, I’m having trouble getting the bullets to come straight out of the point I have set on the tip of the weapon, called bulletSpawnPoint. It’ll shoot straight if the player is facing straight, but shoots backwards when facing left, right, or backwards.
void Update()
{
//Player face mouse
Plane playerPlane = new Plane(Vector3.up, transform.position);
Ray ray = UnityEngine.Camera.main.ScreenPointToRay(Input.mousePosition);
float hitDist = 0.0f;
if(playerPlane.Raycast(ray, out hitDist))
{
Vector3 targetPoint = ray.GetPoint(hitDist);
Quaternion targetRotation = Quaternion.LookRotation(targetPoint - transform.position);
targetRotation.x = 0;
targetRotation.z = 0;
playerObj.transform.rotation = Quaternion.Slerp(playerObj.transform.rotation, targetRotation, 7f * Time.deltaTime);
}
//Player Movement
if (Input.GetKey(KeyCode.W))
{
transform.Translate(Vector3.forward * movementSpeed * Time.deltaTime);
}
if (Input.GetKey(KeyCode.A))
{
transform.Translate(Vector3.left * movementSpeed * Time.deltaTime);
}
if (Input.GetKey(KeyCode.S))
{
transform.Translate(Vector3.back * movementSpeed * Time.deltaTime);
}
if (Input.GetKey(KeyCode.D))
{
transform.Translate(Vector3.right * movementSpeed * Time.deltaTime);
}
//Shooting
if (Input.GetMouseButtonDown(0))
{
Shoot();
gunAudio.Play();
}
}
void Shoot()
{
Instantiate(bullet, bulletSpawnPoint.transform.position, playerObj.transform.rotation);
}
I was told that using a Vector3 when instantiating my bullet would fix this. But how would I do this? Everything I’ve tried gives me an error or makes it so the bullet doesn’t come out of the tip of the weapon