I am trying to make an FPS. But, when I shoot, the bullet is facing the wrong way. It is shooting along the raycast line. But that’s really it. It’s not facing forward, instead, facing sideways. I have attached an image.
Here is the main code.
using UnityEngine;
public class PlayerShooting : MonoBehaviour
{
public GameObject bulletPrefab;
public Transform bulletSpawn;
public float bulletSpeed = 20f;
public float cooldownTime = 1f;
private float lastShootTime = 0f;
void Update()
{
if (Input.GetMouseButtonDown(0) && Time.time >= lastShootTime + cooldownTime)
{
Shoot();
lastShootTime = Time.time;
}
}
void Shoot()
{
RaycastHit hit;
Vector3 shootDirection;
if (Physics.Raycast(bulletSpawn.position, bulletSpawn.forward, out hit))
{
shootDirection = (hit.point - bulletSpawn.position).normalized;
}
else
{
shootDirection = bulletSpawn.forward;
}
GameObject bullet = Instantiate(bulletPrefab, bulletSpawn.position, Quaternion.identity);
bullet.transform.rotation = Quaternion.LookRotation(shootDirection);
BulletMovement bulletMovement = bullet.GetComponent<BulletMovement>();
if (bulletMovement != null)
{
bulletMovement.Initialize(shootDirection);
bulletMovement.speed = bulletSpeed;
}
}
void OnDrawGizmos()
{
Gizmos.color = Color.red;
Gizmos.DrawRay(bulletSpawn.position, bulletSpawn.forward * 100);
}
}
Right here is the code for my attempt at fixing said issue.
using UnityEngine;
public class BulletMovement : MonoBehaviour
{
public float speed = 20f;
private Vector3 direction;
public void Initialize(Vector3 shootDirection)
{
direction = shootDirection.normalized;
}
void Update()
{
transform.position += direction * speed * Time.deltaTime;
}
}
