So, I'm trying to make a 3D shooter and I'm facing a problem where the bullets are not going towards the center of the screen. They're depending on the BulletEffect position.
void Shoot()
{
BulletEffect.Play();
Bun.Play("RifleShoot");
Src.PlayOneShot(Clip);
GameObject Bullet2 = Instantiate(Bullet, BulletEffect.transform.position, Quaternion.identity);
Vector3 direction = GetDirectionToCenter();
Rigidbody BulletRb = Bullet2.GetComponent<Rigidbody>();
BulletRb.velocity = direction * BulletSpeed;
/*RaycastHit hit;
if (Physics.Raycast(Cam.transform.position, Cam.transform.forward, out hit, Range, Layer))
{
Debug.Log(hit.transform.name);
hit.transform.GetComponent<EnemyScript>().TakeDamage(Damage);
}
*/
}
Vector3 GetDirectionToCenter()
{
// Get the center of the screen in screen coordinates
Vector3 screenCenter = new Vector3(Screen.width / 2, Screen.height / 2, 0);
// Convert the screen point to a world point
Vector3 worldCenter = Camera.main.ScreenToWorldPoint(screenCenter);
// Calculate the direction from the firePoint to the center of the screen
Vector3 direction = (worldCenter - BulletEffect.transform.position).normalized;
return new Vector3(direction.x, direction.y, 0f);
}
I tried everything but cant seem to solve it
When using
screenCenter.x and screenCenter.y are converted to Ray based on camera position and rotation, while screenCenter.z is Distance from Camera/Position on Ray. So basically if your screenCenter.z == 0 the function will always return camera position. Try putting your cords to x, y and setting z to 200 so the function will return point on the center of screen at distance 200 from camera.