It is necessary for the bullet to be fired at the same angle as the camera, how to do this?

using System.Collections;
using System.Collections.Generic;
using System.Threading;
using Unity.VisualScripting;
using UnityEngine;

public class PlayerController : MonoBehaviour
{
    private float speed = 5f;
    private float mouseX;
    private float jumpVelocity = 5f;
    public float distanceToGround = 0.1f;
    public LayerMask groundLayer;

    public GameObject bullet;
    private float bulletSpeed = 50f;

    bool canJump;
    bool canShoot;

    private Rigidbody rb;
    private CapsuleCollider coll;
    public Transform mCamera;

    void Start()
    {
        rb = GetComponent<Rigidbody>();
        coll = GetComponent<CapsuleCollider>();
        mCamera = GameObject.Find("Main camera").transform;
        Cursor.lockState = CursorLockMode.Locked;
    }

    void Update()
    {
        if (isGrounded() && Input.GetKeyDown(KeyCode.Space))
        {
            Jump();
        }
        if (Input.GetMouseButtonDown(0))
        {
            Fire();
        }
    }
    private void FixedUpdate()
    {
        MovementLogic();
    }
    private void LateUpdate() 
    {
        RotateLogic();
    }
    private void RotateLogic()
    {
        mouseX = Input.GetAxis("Mouse X");
        transform.Rotate(mouseX * Vector3.up);
    }
    private void MovementLogic()
    {
        //currentAction = PlayerAction.Run;
        float moveHorizontal = Input.GetAxis("Horizontal");
        float moveVertical = Input.GetAxis("Vertical");

        Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);

        transform.Translate(movement * speed * Time.fixedDeltaTime);

    }
    private bool isGrounded()
    {
        Vector3 capsuleBottom = new Vector3(coll.bounds.center.x,
            coll.bounds.min.y, coll.bounds.center.z);
        bool grouned = Physics.CheckCapsule(coll.bounds.center, capsuleBottom,distanceToGround,groundLayer,QueryTriggerInteraction.Ignore);
        return grouned;
    }
    private void Jump()
    {
        rb.AddForce(Vector3.up * jumpVelocity, ForceMode.Impulse);
        print("Jump");
    }
    private void Fire()
    {
        GameObject newBullet = Instantiate(bullet,
            transform.position + transform.forward + new Vector3(0, 0.8f) + transform.right,
            mCamera.rotation);
        Rigidbody bulletRb = newBullet.GetComponent<Rigidbody>();

        bulletRb.velocity = transform.forward * bulletSpeed;
    }
}

explain better what you want to do.

if you don’t want to do that look into convert screen to world point

1 Like

Yes, I also came here to say the same….

if you expect the bullet to be fired as if the camera is pointing down the gun, probably… get the camera.forward and apply it to bullet and then tell it go forward

1 Like