Hello.
I’m making a shooter/platform game on Unity, but I have a problem with my bullet directions.
When I fire my gun depending on my default camera angle, my bullets move in a straight line without any problems, but when I turn my player left/right, my bullets go to very different places.
When I turn 180 degrees from my character’s camera angle, the bullets come out from the back of the gun, not from the tip. When I turn left, the weapon shoots from the left side, and when I turn right, the gun shoots from the right side.
Here’s my code block, I can only add one example picture below because I’m newbie here, but I will add a sample picture below showing the direction the bullets go when I fire the gun.
- My weapon code:
public class WeaponControl : MonoBehaviour
{
public LayerMask obstacleLayer;
public Vector3 offset;
RaycastHit hit;
public GameObject bullet;
public Transform firePoint;
private void Update()
{
//Look
if(Physics.Raycast(Camera.main.transform.position, Camera.main.transform.forward, out hit, Mathf.Infinity, obstacleLayer))
{
transform.LookAt(hit.point);
transform.rotation *= Quaternion.Euler(offset);
}
//Fire
if (Input.GetMouseButtonDown(0))
{
GameObject instantiatedBullet = Instantiate(bullet, firePoint.position, firePoint.rotation);
Rigidbody bulletRb = instantiatedBullet.GetComponent<Rigidbody>();
if (bulletRb != null)
{
bulletRb.linearVelocity = firePoint.forward * 30f;
}
}
}
}
- My bullet code:
public class Bullet : MonoBehaviour
{
public float speed = 100f;
private void Update()
{
transform.Translate(transform.forward * Time.deltaTime * speed);
}
}
Bullet directions example;
I started coding one month ago. I wrote these lines of code by researching here and there on the internet, so I may have basic errors :> Can you please explain by simplifying and explaining?