My turrets are driving me nuts [Wrong rotation/Shooting issues]

So I have a turret prefab, of which the turning part I want to follow the player and shoot at him repeatedly.
Now, through following multiple tutorials and writing some of my own code, I was able to get it to;

  • follow the player on the Y axis smoothly, if he enters it’s range
  • instatiate projectiles

However! The turret faces the player on the X axis only slightly, going down only by a few degrees (they seem to “hover” around 0-1.123 etc.) and It was facing away from the player originally, so I have changed the follow on X axis to be on -x, so now it turns towards the player, but the facing issue remains.

Also, the instantiated projectiles drop to the ground, instead of inheriting the give velocity. I had used the same script that worked for my player’s weapon, which still works.

This is the turret’s aiming script + it’s firing script in one. The shell only has a rigidbody, an explode-on-contact script and a capsule collider, which is not a trigger.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SentryAI : MonoBehaviour
{

    public Transform targetingPlayer;

    public GameObject sentryShell;
    public Transform sentryMuzzle; //empty gameObject at the end of a barrel

    [Header ("Attributes")]

    public float range = 15f;
    public float sentryFireRate = 1f;
    private float fireCooldown = 0f;
    public float detterentForce = 80; //force value, that's supposed to be given to the shell

    [Header ("Unity Setup Fields")]

    public Transform partToRotate;
    public float sentrySpeed = 5f;



    public string playerTag = "Player";
    void Start()
    {
        InvokeRepeating("UpdateTarget", 0f, 2f);
    }

    void UpdateTarget()
    {
       

        GameObject[] enemies = GameObject.FindGameObjectsWithTag(playerTag); //Player has an empty gameObject in the lower-mid of his tank with this tag
        float shortestDistance = Mathf.Infinity;
        GameObject nearestEnemy = null;

        foreach (GameObject enemy in enemies)
        {
            float distanceToEnemy = Vector3.Distance(transform.position, enemy.transform.position);
            if (distanceToEnemy < shortestDistance)
            {
                shortestDistance = distanceToEnemy;
                nearestEnemy = enemy;
            }
        }
        // Target nearest enemy - may be unnecessary
        if (nearestEnemy != null && shortestDistance <= range)
        {
            targetingPlayer = nearestEnemy.transform;
        }
        else
        {
            targetingPlayer  = null;
        }
    }

    void Update()
    {
        if (targetingPlayer == null)
            return;
        // This is the lock-on

        Vector3 dir = targetingPlayer.position - transform.position;
        Quaternion lookRotation = Quaternion.LookRotation(dir);
        Vector3 rotation = Quaternion.Lerp(partToRotate.rotation, lookRotation, Time.deltaTime * sentrySpeed).eulerAngles;
        partToRotate.rotation = Quaternion.Euler(rotation.x, rotation.y, 0f); //The rotation X here is supposed to do the same thing as Y, which works, but it only angles by under 2 degrees max

        if(fireCooldown <= 0)
        {
            Engage();
            fireCooldown = 1f / sentryFireRate;
        }

        fireCooldown -= Time.deltaTime;
    }

    void Engage()
    {
        GameObject finstabilized = (GameObject)Instantiate(sentryShell, sentryMuzzle.position, sentryMuzzle.rotation);
        Rigidbody rb = sentryShell.GetComponent<Rigidbody>();
        rb.AddForce(transform.forward * detterentForce, ForceMode.VelocityChange); //this is supposed to add force to the shells - currently they drop to the ground

    }

    private void OnDrawGizmosSelected()
    {
        Gizmos.DrawWireSphere(transform.position, range); 
    }
}

I am running out of time to finish this project - otherwise I’d try to figure it out on my own. Next time, I’ll try to make something even simpler, because it seems I had though-out a too difficult of a project to make and I feel bad about asking so many questions.

These are NOT angles. (EDIT: correction: they actually are eulerAngle degrees in the confusing use case above.) These are internal parts of a Quaternion. Never mess with them unless you have published a doctorate-thesis level peer-approved paper on how Quaternions work at the lowest math level.

Perhaps you want rotation.eulerAngles.x ?

Just beware of gimbal lock.

https://starmanta.gitbooks.io/unitytipsredux/content/second-question.html

Oh, I actually have that last link saved as something I’ll read once there’s time.

But that doesen’t explain why it’s working on y axis and it’s partially from the Brackies tutorial on a tower-defense turret AI, so it should be correct. They’ve said the function lookRotation.eulerAngles should make it in Euler angles, so why does it only rotate around one axis properly?

I actually read the code more and line 69 actually is making a rotation (via Lerp) and then taking the eulerAngles. While we’re at it, make shorter lines. :slight_smile:

I honestly don’t even know what to tell you about the above code because it looks like it has waaaaay too many moving parts.

This was my solution to 3D turret aiming/rotating:

At the end of the day:

  • use Atan2() to find the angle in degrees
  • use MoveTowards (or Lerp) to smoothly change the angle
  • use Quaternion.Euler() to create rotations for the angle

Smoothing movement between any two particular values:

You have currentQuantity and desiredQuantity.

  • only set desiredQuantity
  • the code always moves currentQuantity towards desiredQuantity
  • read currentQuantity for the smoothed value

Works for floats, Vectors, Colors, Quaternions, anything continuous or lerp-able.

The code: SmoothMovement.cs · GitHub

For score count-up (like a cash register whizzing lots of numbers upwards), I like this approach:

To figure out what is actually happening in your code above, same rules apply:

What is often happening in these cases is one of the following:

  • the code you think is executing is not actually executing at all
  • the code is executing far EARLIER or LATER than you think
  • the code is executing far LESS OFTEN than you think
  • the code is executing far MORE OFTEN than you think
  • the code is executing on another GameObject than you think it is
  • you’re getting an error or warning and you haven’t noticed it in the console window

To help gain more insight into your problem, I recommend liberally sprinkling Debug.Log() statements through your code to display information in realtime.

Doing this should help you answer these types of questions:

  • is this code even running? which parts are running? how often does it run? what order does it run in?
  • what are the values of the variables involved? Are they initialized? Are the values reasonable?
  • are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

Knowing this information will help you reason about the behavior you are seeing.

If your problem would benefit from in-scene or in-game visualization, Debug.DrawRay() or Debug.DrawLine() can help you visualize things like rays (used in raycasting) or distances.

You can also call Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene manually, looking for all the parts, where they are, what scripts are on them, etc.

You can also call GameObject.CreatePrimitive() to emplace debug-marker-ish objects in the scene at runtime.

You could also just display various important quantities in UI Text elements to watch them change as you play the game.

If you are running a mobile device you can also view the console output. Google for how on your particular mobile target, such as this answer or iOS: How To - Capturing Device Logs on iOS or this answer for Android: How To - Capturing Device Logs on Android

Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.

Here’s an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

You must find a way to get the information you need in order to reason about what the problem is.