transform.LookAt() makes object flip around when too close? (FPS Gun Position Question)
Hello, I'm new to coding and I'm creating little test scripts to challenge what I'm learning. I'm attempting to make a gun script, where the player emits a raycast from the main camera (representing the weapon range), and if it hits something, the gun rotates to aim at the hit.Point. If nothing is touching the raycast, the gun should sit in the default position and just shoot forward from the barrel if fired. I have a script that kind of accomplishes this, but whenever I look too far down, the gun rotates 100+ degrees on the y-axis (and less so on the other 2 axis), moving out of the screen and aiming it at a very weird position. When you get too close to a wall, it angles up a little too much and begins glitching in and out. I suspect this is happening because the gun is getting too close to the ground, and creates an issue with the transform.LookAt() line? Here are the most relevant parts of my code, I can provide more if needed.
private void FixedUpdate()
{
Vector3 rayOrigin = fpsCam.ViewportToWorldPoint(new Vector3(0.5f, 0.5f, 0));
Ray ray = new Ray(rayOrigin, fpsCam.transform.forward);
RaycastHit hitInfo;
if (isReloading)
{
return;
}
if (Physics.Raycast(ray, out hitInfo, weaponRange)) //Rotate gun towards hitInfo.Point
{
shotgun.transform.LookAt(hitInfo.point);
if (Input.GetMouseButtonDown(0) && Time.time > nextFire)
{
nextFire = Time.time + fireRate;
Debug.Log("Aim at " + hitInfo.transform.name);
GameObject bulletCreate = Instantiate(bullet);
bulletCreate.transform.position = barrel.transform.position + fpsCam.transform.forward;
bulletCreate.transform.forward = barrel.transform.forward;
currentAmmo--;
}
}
else if (Input.GetMouseButtonDown(0) && Time.time > nextFire) //Shoot freely
{
nextFire = Time.time + fireRate;
Debug.Log("Hip fire");
GameObject bulletCreate = Instantiate(bullet);
bulletCreate.transform.position = barrel.transform.position + fpsCam.transform.forward;
bulletCreate.transform.forward = barrel.transform.forward;
currentAmmo--;
}
The line in question that I believe is causing the issues is
shotgun.transform.LookAt(hitInfo.point);
However with my sloppy code and inexperience, I suspect I'm creating many errors that are feeding this one. Should I abandon this script and start fresh, or can this be done?
Your answer
![](https://koobas.hobune.stream/wayback/20220613011701im_/https://answers.unity.com/themes/thub/images/avi.jpg)