I just implemented a shooting mechanism into my gun where bullets are created and move out of the barrel of the gun forwards and since they come from the barrel, their direction doesn’t match the crosshair in the middle of the screen.
How can I make the bullets move so you can aim with the crosshair?
Hello @romans8710
You can solve it using raycasting:
//Create a ray. Syntax: Physics.Raycast(startPosition, direction, hitInfo)
Physics.Raycast(yourCamera.transform.position, yourCamera.transform.forward, RaycastHit hitInfo);
//the code you wrote now
bullet.AddComponent(typeof(Rigidbody));
Rigidbody rb = bullet.GetComponent<Rigidbody>();
rb.useGravity = false;
//Rotate the bullet towards the point where the ray hits a collider
bullet.transform.LookAt(hitInfo.point);
//It is better to add a force, not to modify velocity.
rb.AddForce(bullet.transform.forward * speed, ForceMode.VelocityChange);
It can have a weird effect if you are close to the target, but should work. If you want to learn more about raycasting, there is a on YouTube made by Unity about it.